有关ruby类中方法顺序的规则是什么。看一下Michael Hartl的Rails教程中的这个例子。以下代码片段在create方法调用micropost_params方法的情况下工作得很好。但是,私有方法首先列在文件的底部。
class MicropostsController < ApplicationController
before_action :signed_in_user
before_action :correct_user, only: :destroy
def create
@micropost = current_user.microposts.build(micropost_params)
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to root_url
else
@feed_items = []
render 'static_pages/home'
end
end
def destroy
@micropost.destroy
redirect_to root_url
end
private
def micropost_params
params.require(:micropost).permit(:content)
end
def correct_user
@micropost = current_user.microposts.find_by(id: params[:id])
redirect_to root_url if @micropost.nil?
end
end
然而,我现在正在尝试编写的代码给了我一个no方法错误。据推测,这是因为由于代码中的位置,该方法尚未定义。也许还有另一种解释。请指教。
class WeatherModel
def self.getWeatherProjections(field_names)
@tablename = "myProjections"
getWeatherData(field_names)
end
def self.getWeatherDailyAct(field_names)
@tablename = "WeatherDaily"
#getWeatherData(field_names)
end
def self.getWeatherHourlyAct(field_names)
@tablename = "WeatherHourly"
#getWeatherData(field_names)
end
private
def getWeatherData(field_names)
if isActive? && (not field_names.nil?)
if not field_names.empty?
field_names.inject("field_names[0].to_s") { |set,name| set+="{#{name},"}
else
set="*"
end
@client.execute("SELECT #{set} FROM [#{table_name}]")
else
init
end
end
def init
@client = TinyTds::Client.new username: 'blah', password: 'blah', host: 'blah', database: 'blah'
end
def isActive?
@client.active?
end
end
可能是因为我没有计算得到一些类/实例方法的细节。 self.method可以不调用实例方法吗?请有人解释一下这个谜团。哦,我得到的错误是:
2.1.4 :006 > WeatherModel.getWeatherProjections([])
NoMethodError: undefined method `getWeatherData' for WeatherModel:Class
from /Users/forresce/Dev/guc_scadagas_rails/app/models/weather_model.rb:5:in `getWeatherProjections'