Configure class with block

I have a basic module that has some logic in it and is included inside different classes. Now I need a block configurethat sets up some configuration of how the class should behave.

I tried the following code:

class MyConfig
  attr_accessor :foo, :bar
end

module BaseModule
  def self.included base
    base.include InstanceMethods
    base.extend ClassMethods
  end

  module ClassMethods
    attr_reader :config

    def configure &block
      @config = MyConfig.new
      block.call(@config)
    end
  end

  module InstanceMethods
    def do_something
      puts self.class.config.inspect
    end
  end
end

class MyClass1
  include BaseModule

  configure do |config|
    config.foo = "foo"
  end
end

class MyClass2
  include BaseModule

  configure do |config|
    config.bar = "bar"
  end
end

MyClass1.new.do_something
#<MyConfig:0x007fa052877ea0 @foo="foo">
MyClass2.new.do_something
#<MyConfig:0x007fa052877ce8 @bar="bar">
  • I'm not sure if an instance variable @configfor a module / class is the best way to set up a class. Is this right, or are there better solutions?
  • Is it good to use base.extend ClassMethodswhen the module is turned on only with include BaseModule? A developer might expect that only instance methods are included, but as a side effect there are also extended class methods.

Update

MyConfig, . , config.foo = "foo".

+4
1

, , (, ) . , :)

module BaseModule
  def self.included base
    base.include InstanceMethods
    base.extend ClassMethods
  end

  module ClassMethods
    mattr_accessor :foo
    @@foo = 'initial value'

    def configure &block
      block.call(self)
    end
  end

  module InstanceMethods
    def do_something
      puts foo
    end
  end
end

class MyClass1
  include BaseModule

  configure do |klass|
    klass.foo = "foo"
  end
end

class MyClass2
  include BaseModule

  configure do |klass|
    klass.foo = "bar"
  end
end

MyClass1.new.do_something
# => "foo"
MyClass2.new.do_something
# => "bar"

:

  • use mattr_accessor - , , , ,
  • let configure return self, , , .

:

Kid.config do |k|
  k.be_kind = false
  k.munch_loudly = true
  k.age = 12
end
0

Source: https://habr.com/ru/post/1623892/


All Articles