2017-08-03 54 views
0

我想有哪些可以包含在类模块,并允许这样的设置选项:定义一个类的方法选项类似行动梅勒类不

class MyService 
    include Healthcheck 

    healthcheck_id 'foobar' 
end 

,模块也会看起来是像:

module Healthcheck 
    extend ActiveSupport::Concern 

    included do 
    def self.healthcheck_id(value) 
     # What do I do here? 
    end 
    end 
end 

的问题是:我怎么保存这个值被传递作为参数,这样我以后可以用吗?

也许有些情况下可能会帮助在这里,我的灵感来自于行动梅勒:

class ExampleMailer < ActionMailer::Base 
    default from: "[email protected]" 
end 

在上述类方法default是接受哈希带参数,显然from所使用的动作梅勒时的例子(?)电子邮件正在发送。

回答

2

@hieu-pham的解决方案PB是,你不能定义不同healthcheck_id为不同类别的值:

class MyService1 
    include Healthcheck 

    healthcheck_id 'foobar_1' 

    def foo 
    puts healthcheck_id_value 
    end 
end 

class MyService2 
    include Healthcheck 

    healthcheck_id 'foobar_2' 

    def foo 
    puts healthcheck_id_value 
    end 
end 

MyService1.new.foo # foobar_2 
MyService2.new.foo # foobar_2 

一个更好的解决办法是:

module Healthcheck 
    extend ActiveSupport::Concern 

    included do 
    class_attribute :healthcheck_id_value 

    def self.healthcheck_id(value) 
     self.healthcheck_id_value = value 
    end 

    def self.foo 
     healthcheck_id_value 
    end 
    end 
end 

class MyService1 
    include Healthcheck 

    healthcheck_id 'foobar_1' 
end 

class MyService2 
    include Healthcheck 

    healthcheck_id 'foobar_2' 
end 

MyService1.foo # foobar_1 
MyService2.foo # foobar_2 
0

储存于一个类变量

@@arguments_passed = value

1

您可以使用类变量来做到这一点,所以代码会成为:

module Healthcheck 
    extend ActiveSupport::Concern 

    included do 
    def self.healthcheck_id(value) 
     @@healthcheck_id_value = value 
    end 

    class_eval do 
     def healthcheck_id_value 
     self.class.class_variable_get(:@@healthcheck_id_value) 
     end 
    end 
    end 
end 

所以从现在开始,您可以访问healthcheck_id_value,例如:

class MyService 
    include Healthcheck 

    healthcheck_id 'foobar' 

    def foo 
    puts healthcheck_id_value 
    end 
end 

让我们称之为MyService.new.foo,它将打印“foobar的”

+0

不要说不要使用类变量,只要小心他们周围的子类:'类MySubService 'barfoo'; MySubService.new.foo#=>'barfoo'' –