0
module Framework
 class CreateTableDefinition 
   attr_accessor :host, :username, :password
 end 
end

def create_table(table_name)
  obj = Framework::CreateTableDefinition.new
  yield(obj) if block_given?
end

create_table :users do |config|
  config.host :localhost
end

And here is the error I get

-:13:in `block in <main>': wrong number of arguments (1 for 0) (ArgumentError)
    from -:9:in `create_table'
    from -:12:in `<main>'

If I change the code to

config.host = :localhost

it works fine. But what I want is to work as described above config.host :localhost

2
  • It sounds like you want the CreateTableDefinition class to have a host method that assigns its argument to the @host local, does that sound right? Commented Aug 8, 2014 at 17:21
  • @AndrewPiliser, correct but I want to ommit the = I spot that most of the RoR code make the assignments like that config.host :localhost. See no = Commented Aug 8, 2014 at 17:25

2 Answers 2

2

You missed assignment:

config.host = :localhost

Edit

If you want to get rid of assignments, you need to define setter methods without = at the end. This might generate quote a lot of code, so I would rather go with some meta-programming (because it's fun!)

class MyConfigClass
  def self.attributes(*args)
    args.each do |attr|
      define_method attr do |value|
        @attributes[attr] = value
      end
    end
  end

  def initialize
    @attributes = {}
  end

  def get(attr)
     @attributes[attr]
  end 
end

class CreateTableDefinition < MyConfigClass
   attributes :host, :username, :password
end

c = CreateTableDefinition.new
c.host :localhost
c.get(:host)   #=> :localhost 
Sign up to request clarification or add additional context in comments.

2 Comments

I know that but how to do to work with config.host :localhost? I'm learning ruby and notice that most of the RoR blocks make the assignment in that way
@MZON - I wouldn't say most, rails config uses standard assignments. I'll update the question with how to do that in a second.
0

Try manually making a method that does what you want instead of using the attr_accessor shortcut.

class CreateTableDefinition 
  attr_accessor :username, :password

  def host(sym)
    @host = sym
  end

  def get_host
    @host
  end
end

If you don't like the idea of writing those methods for every attribute, look into writing your own helper, something like attr_rails_like, and mix it in to the Class object. This article might be helpful.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.