Suppose you have this code from the ActiveSupport :: Concern documentation, but you want the included Foo block to have something different depending on the module or class, including Foo.
In the specific problem I'm trying to solve, I have a set of validations for addresses, but the address fields will be called home_zip_code or work_zip_code, and I want the inclusion of validation to confirm the zip_code field prefix.
require 'active_support/concern'
module Foo
extend ActiveSupport::Concern
included do
def self.method_injected_by_foo
...
end
end
end
module Bar
extend ActiveSupport::Concern
include Foo
included do
self.method_injected_by_foo
end
end
class Host
include Bar
end
I posted this discussion here: http://forum.railsonmaui.com/t/how-make-a-concern-parameterized/173
The following two work options. I wonder which is preferable.
Concern Using Class Method
This is the problem that needs to be "parameterized":
module Addressable
extend ActiveSupport::Concern
included do
zip_field = "#{address_prefix}_zip_code".to_sym
zip_code_regexp = /^\d{5}(?:[-\s]\d{4})?$/
validates zip_field, format: zip_code_regexp, allow_blank: true
end
address_prefix Addressable.
cattr_accessor :address_prefix
self.address_prefix = "home"
include Addressable
def self.address_prefix
"home"
end
include Addressable
self.append_features .
def self.append_features(base)
base.class_eval do
def self.address_prefix
"home"
end
end
super
end
def self.append_features(base)
base.cattr_accessor :address_prefix
base.address_prefix = "home"
super
end
- ,
cattr_accessor ? self.append_features ?class_eval , class exec? , . .- , , "work" "home", . , . , ? ?