ruby on rails accessing custom class attributes from its object - ruby-on-rails

I have a custom class in my application controller. Like below:
class Defaults
def initialize
#value_1 = "1234"
#value_2 = nil
#data = Data.new
end
end
class Data
def initialize
#data_1 = nil
end
end
Now in my controller method i have created an object of type Defaults
def updateDefaultValues
defaults = Defaults.new
# i am unable to update the value, it says undefined method
defaults.value_2 = Table.maximum("price")
defaults.data.data_1 = defaults.value_2 * 0.3
end
How to access value_2 from defaults object?
defaults.value_2
Also, how to access data_1 attribute from data object within defaults object?
defaults.data.data_1

You should use attr_accessor:
class Defaults
attr_accessor :value_1, :value_2, :data
# ...
end
defaults = Defaults.new
defaults.value_1 = 1
# => 1
defaults.value_1
# => 1

As you are using def as a keyword to define the method, that means def is a reserved keyword. You can't use reserved keywords as a variable.
You just need to rename your variable name from def to something_else and it should work! Your code will look like this:
def updateDefaultValues
obj = Defaults.new
obj.value_2 = Table.maximum("price")
obj.data.data_1
end
EDIT:
As per OP's comment & updated question, he had used def just as an example, here is the updated answer:
You may need attr_accessor to make attrs accessible:
class Defaults
attr_accessor :value_1, :value_2, :data
...
...
end
class Data
attr_accessor :data_1
...
...
end

Add value_2 method in Defaults class
class Defaults
def initialize
#value_1 = "1234"
#value_2 = nil
#data = Data.new
end
def value_2
#value_2
end
end
class Data
def initialize
#data_1 = nil
end
end

Related

Passing variables between classes in Ruby on Rails

So I have two files, one called a.rb and one called b.rb. Here's the contents in both:
# a.rb
class A
def initialize
#variable = ""
#module_b = B.new(self)
end
def pass_to_b(self)
#module_b.do_something(#variable)
end
def set_variable(var)
# var = empty
#variable = var
end
end
and
# b.rb
class B
def initialize(module_a)
#module_a = module_a
end
def set_variable_in_a(data)
#module_a.set_variable(data)
end
def do_something(variable)
# variable = empty
set_variable_in_a("hello world")
end
end
This is just an example of what I'm dealing with. If I'm trying to start a function in Class A, which is supposed to do something in ClassB and then change an instance variable in Class A, I'm not sure how to do this properly. This is what I've tried, however:
a = A.new
a.pass_to_b
Class B cannot see the instance variable #variable, and if it tries to set_variable_in_a, that doesn't work either. It's like the do_something function in Class A successfully calls the do_something function in Class B, but the instance variable information is not available. I thought by passing self to Class B, we'd be able to at least call the function
My MRI throws exeption about
def pass_to_b(self)
because you can't pass self to method as argument.
You need delete 'self' how argument
Run code below and you will see that #variable of instance of Class A has '123hello world' string
class A
def initialize
#variable = "123"
#module_b = B.new(self)
end
def pass_to_b
#module_b.do_something(#variable)
end
def set_variable(var)
# var = empty
#variable = var
end
end
# b.rb
class B
def initialize(module_a)
#module_a = module_a
end
def set_variable_in_a(data)
#module_a.set_variable(data)
end
def do_something(variable)
set_variable_in_a(variable + "hello world")
end
end
a = A.new
a.pass_to_b
display variable 'a' and you will see something like this
#<A:0x00007fdaba0f3c90 #variable="123hello world", #module_b=#<B:0x00007fdaba0f3c40 #module_a=#<A:0x00007fdaba0f3c90 ...>>>

Extending ActiveModel::Serializer with custom attributes method

I am trying to create my own attributes method called secure_attributes where I pass it an array of attributes and the minimum level the authorized user needs to be to view those attributes. I pass the current level of the authorized user as an instance_option. I'd like to extend the Serializer class so I can use this method in multiple serializers, but Im having issues.
This is what i have so far:
in config/initializers/secure_attributes.rb
module ActiveModel
class Serializer
def self.secure_attributes(attributes={}, minimum_level)
attributes.delete_if {|attr| attr == :attribute_name } unless has_access?(minimum_level)
attributes.each_with_object({}) do |name, hash|
unless self.class._fragmented
hash[name] = send(name)
else
hash[name] = self.class._fragmented.public_send(name)
end
end
end
end
end
and then in the individual serializer I have things like this:
secure_attributes([:id, :name, :password_hint], :guest)
and then
def has_access?(minimum_level=nil)
return false unless minimum_level
return true # based on a bunch of logic...
end
But obviously secure_attributes cannot see the has_access? method and if I put has_access inside the Serializer class, it cannot access the instance_options.
Any idea how I can accomplish what I need?
Maybe you want to do following - but I still do not get your real purpose, since you never did anything with the attributes but calling them:
module ActiveRecord
class JoshsSerializer < Serializer
class << self
def secure_attributes(attributes={}, minimum_level)
#secure_attributes = attributes
#minimum_level = minimum_level
end
attr_reader :minimum_level, :secure_attributes
end
def initialize(attr, options)
super attr, options
secure_attributes = self.class.secure_attributes.dup
secure_attributes.delete :attribute_name unless has_access?(self.class.minimum_level)
secure_attributes.each_with_object({}) do |name, hash|
if self.class._fragmented
hash[name] = self.class._fragmented.public_send(name)
else
hash[name] = send(name)
end
end
def has_access?(minimum_level=nil)
return false unless minimum_level
return true # based on a bunch of logic...
end
end
end

Pointer on class object

In my Ruby model I want to apply default value on somes properties on my Recipe. So I added an before_save callback to apply it: This is my Recipe model:
class Recipe < ActiveRecord::Base
before_save :set_default_time
# other stuff
private
# set default time on t_baking, t_cooling, t_cooking, t_rest if not already set
def set_default_time
zero_time = Time.new 2000, 1 ,1,0,0,0
self.t_baking = zero_time unless self.t_baking.present?
self.t_cooling = zero_time unless self.t_cooling.present?
self.t_cooking = zero_time unless self.t_cooking.present?
self.t_rest = zero_time unless self.t_rest.present?
end
end
It's pretty work but I want to factorize it like this:
class Recipe < ActiveRecord::Base
before_save :set_default_time
# other stuff
private
# set default time on t_baking, t_cooling, t_cooking, t_rest if not already set
def set_default_time
zero_time = Time.new 2000, 1 ,1,0,0,0
[self.t_baking, self.t_cooling, self.t_cooking, self.t_rest].each{ |t_time|
t_time = zero_time unless t_time.present?
}
end
end
But it doesn't work. How can I loop on "pointer" on my object propertie?
it won't work because you refer strictly to value, thus your override doesn't work as expected. you may try this:
[:t_baking, :t_cooling, :t_cooking, :t_rest].each { |t_time|
self.send("#{t_time}=".to_sym, zero_time) unless self.send(t_time).present?
}

Access varible in ruby after initialize

I am trying to access variable in ruby after initialize, but i didn't get that variable , anything wrong in that?
class Test
def initialize(params)
#has_test = params[:has_test]
#limit_test = params[:limit_test]
end
def self.method1(params)
Test.new(params)
#can i get that two instance variable
end
end
You should probably set up attribute accessors, then use them this way:
class Test
attr_accessor :has_test
attr_accessor :limit_test
def initialize(params)
#has_test = params[:has_test]
#limit_test = params[:limit_test]
end
def self.method1(params)
t = Test.new(params)
// can i get that two instance variable
// Yes:
// use t.has_test and t.limit_test
end
end
You are mixing an instance and a class method in your example.
If this is really what you want, then you have to define an accessor with attr_reader:
class Test
def initialize(params)
#has_test = params[:has_test]
#limit_test = params[:limit_test]
end
attr_reader :has_test
attr_reader :limit_test
def self.method1(params)
obj = Test.new(params)
p obj.has_test
p obj.limit_test
end
end
Test.method1(has_test: 1, limit_test: 3)
It the instance/class-method is a mistake, then this example may help you:
class Test
def initialize(params)
#has_test = params[:has_test]
#limit_test = params[:limit_test]
end
def method1()
p #has_test
p #limit_test
end
end
obj = Test.new(has_test: 1, limit_test: 3)
obj.method1
If you define also the accessors like in the first code, then you have again access from outside the class.
Just in case you don't want a reader, see also Access instance variable from outside the class

Rails: ActiveRecord interdependent attributes setters

In activerecord, attribute setters seems to be called in order of the param hash.
Therefore, in the following sample, "par_prio" will be empty in "par1" setter.
class MyModel < ActiveRecord::Base
def par1=(value)
Rails.logger.info("second param: #{self.par_prio}")
super(value)
end
end
MyModel.new({ :par1 => 'bla', :par_prio => 'bouh' })
Is there any way to simply define an order on attributes in the model ?
NOTE: I have a solution, but not "generic", by overriding the initialize method on "MyModel":
def initialize(attributes = {}, options = {})
if attributes[:par_prio]
value = attributes.delete(:par_prio)
attributes = { :par_prio => value }.merge(attributes)
end
super(attributes, options)
end
Moreover, it does not works if par_prio is another model that has a relation on, and is used to build MyModel:
class ParPrio < ActiveRecord::Base
has_many my_models
end
par_prio = ParPrio.create
par_prio.my_models.build(:par1 => 'blah')
The par_prio param will not be available in the initialize override.
Override assign_attributes on the specific model where you need the assignments to happen in a specific order:
attr_accessor :first_attr # Attr that needs to be assigned first
attr_accessor :second_attr # Attr that needs to be assigned second
def assign_attributes(new_attributes, options = {})
sorted_new_attributes = new_attributes.with_indifferent_access
if sorted_new_attributes.has_key?(:second_attr)
first_attr_val = sorted_new_attributes.delete :first_attr
raise ArgumentError.new('YourModel#assign_attributes :: second_attr assigned without first_attr') unless first_attr_val.present?
new_attributes = Hash[:first_attr, first_attr_val].merge(sorted_new_attributes)
end
super(new_attributes, options = {})
end

Resources