简体   繁体   中英

Passing parameters to ruby methods in Rails

I have method inside AplicationController which I want to be reusable from all controllers:

 class AplicationController < ActionController::Base protected def set_cartridge_values(cartridge, cartridge_value, param_value) @quantity = cartridge.cartridge_value.to_i + param_value.to_i cartridge.update(cartridge_value: @quantity) end 

I in some controller I want to cal this method like that:

 set_cartridge_values(@cartridge, ? ,params[:toner_kg][:weight]) 

In place of ? mark I dont know how to pass that parameter.

@cartridge - is a varaible defined before

params[:toner_kg][:weight] - is a value

and cartridge_value - is a attribute of a cartridge.

For example I want to pass toner_gr attribute of a cartridge model and update that attribute.

I think the following should work for you:

def set_cartridge_values(cartridge, attribute, value)
  @quantity = cartridge.send(cartridge_attribute).to_i + value.to_i
  cartridge.update(cartridge_value => quantity)
end

And you call that method like:

set_cartridge_values(@cartridge, :toner_gr, params[:toner_kg][:weight])

Or you could use increment! what makes is so short that there is not really a need for an extra method:

@cartridge.increment!(:toner_gr, params[:toner_kg][:weight].to_i)

Instead of send you could also use

def set_cartridge_values(cartridge, cartridge_attribute, value)
  @quantity = cartridge[cartridge_attribute].to_i + value.to_i
  cartridge.update(cartridge_value => quantity)
end

Another option is using read_attribute

@quantity = cartridge.read_attribute(cartridge_attribute).to_i + value.to_i

You should use public_send if it is should access only public methods of the instance.

@quantity = cartridge.public_send(cartridge_attribute).to_i + value.to_i

So possible options are,

 cartridge[cartridge_attribute]
 cartridge.read_attribute(cartridge_attribute)
 cartridge.public_send(cartridge_attribute)
 cartridge.send(cartridge_attribute)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM