0

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.

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

isn't increment deprecated?
Oh yes, that is the old method on ActiveRecord::Base which was removed in Rails 3. Since Rails 3 there is a new method defined on ActiveRecord::Persistence (see link in my answer) which does the same.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.