Vinay Kashyap T S
Vinay Kashyap T S

Reputation: 595

ruby on rails accessing custom class attributes from its object

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

Upvotes: 0

Views: 1672

Answers (3)

RAJ
RAJ

Reputation: 9747

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

Upvotes: 0

Sachin R
Sachin R

Reputation: 11876

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

Upvotes: -1

Marek Lipka
Marek Lipka

Reputation: 51151

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

Upvotes: 4

Related Questions