gpt4 book ai didi

ruby-on-rails - send() 方法的用途是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 06:25:01 28 4
gpt4 key购买 nike

有人可以帮我理解下面列出的“send()”方法的用途吗?当我阅读下面的代码时,它的用途毫无意义。

这是一个 Rails 应用程序,使用 Ruby 1.8.7 和 Rails 1.2.3。请不要跟我唠叨升级,这是客户的环境,我没有那种闲暇。

不用说,我指的是这样的说法;

def do_schedule
@performance = Performance.new(params[:performance])
@performer = Performer.find(params[:performer_id])
selected_track = params[:selected_track]
if FileTest.exists?(File.expand_path(@performer.photo))
@performance.photo = File.open(File.expand_path(@performer.photo))
end

@performance.audio = File.open(File.expand_path(@performer.send(selected_track)))

if @performance.save
flash[:notice] = 'Performer scheduled.'
redirect_to :controller => :performer, :action => :index
else
render :action => 'schedule'
end
end

表演者模型

class Performer < ActiveRecord::Base
file_column :audio_one
file_column :audio_two
file_column :audio_three
file_column :photo

belongs_to :festival
validates_presence_of :name, :first_name, :last_name, :address, :city, :state, :zip, :daytime_phone, :availability, :stages
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
validates_confirmation_of :email

validates_presence_of :audio_one, :audio_two, :audio_three, :photo, :if => :submitted

after_create :salt_access_key
serialize :availability
serialize :stages

attr_accessor :other_type_of_music
before_save :set_other_type

def set_other_type
if type_of_music == 'Other'
self.type_of_music = "Other - #{other_type_of_music}" unless other_type_of_music.blank?
end
end

def salt_access_key
update_attribute(:access_key, Digest::SHA1.hexdigest("--#{self.id}--#{self.name}--#{self.festival.year}"))
end

def preferred_stages
stages = []
festival = Festival.find(self.festival_id.to_i)
self.stages.collect { | key, value |
id = key.gsub(/[\D]/, '').to_i
if id > 0
stages << festival.performance_stages.find(id).name
end
}
return stages
end
end

包含这个的 Controller 是Performance。我一直在谷歌上搜索,试图弄清楚“@performer.send(selected_track)”的实际用途,但我觉得自己正在与漩涡划桨。

最佳答案

用于向对象发送方法消息的 send 方法的 Ruby 实现是这样工作的:

class Car

def start
puts "vroom"
end

private

def engine_temp
puts "Just Right"
end

end

@car = Car.new
@car.start # output: vroom
@car.send(:start) # output: vroom

这是基础知识,另外一条重要信息是 send 允许您将消息发送到 PRIVATE 方法,而不仅仅是公共(public)方法。

@car.engine_temp  # This doesn't work, it will raise an exception
@car.send(:engine_temp) # output: Just Right

至于您的特定发送调用将做什么,很可能在 Performer 类中有一个 def method_missing 被设置为捕获它并执行一些操作。

关于ruby-on-rails - send() 方法的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7895253/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com