使用Action Mailer中的类方法定义选项

时间:2017-08-03 10:41:47

标签: ruby-on-rails ruby

我想要一个可以包含在课堂中的模块,并允许设置这样的选项:

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

问题是:如何存储作为参数传递的值,以便以后可以使用它?

也许某些背景可能有所帮助,我受到了Action Mailer的启发:

class ExampleMailer < ActionMailer::Base
  default from: "no-reply@example.com"
end

在上面的示例中,类方法(?)default接受带参数的哈希,并且在发送电子邮件时,Action Mailer显然使用from

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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'

答案 2 :(得分:0)

将其存储在类变量

@@arguments_passed = value

答案 3 :(得分:0)