Use the "concerns" pattern in any Ruby or Rails project.
In Gemfile:
gem 'concerned'
This gem comes with the following three helpers, that are added to Module
. To require concern modules (or classes)
And to include concern modules
class FixtureUser
include_concerns :scopes, :validations
end
The include_concerns
helper method can be made to find a module or class matching the current namespace, using the ns
option. The following will include FixtureUser::Scopes
and FixtureUser::Validations
into FixtureUser
.
class FixtureUser
include_concerns :scopes, :validations, ns: true
end
You can specify a specific namespace by using ns
, for
or from
with a string indicicating the namespace (will be camelized).
class FixtureUser
include_concerns :scopes, :validations, from: 'Fixture'
end
The include_shared_concerns
expects to find a module in a shared
folder somewhere in the load path that has a name of either Caching
or Shared::Caching
for the following example:
class FixtureUser
include_shared_concerns :caching
end
The concerned_with
and shared_concerns
methods are used simply to require shared files following the namespace convention, here: project/job_matches
and shared/associations
.
class Project
concerned_with :job_matches
shared_concerns :associations
end
You can now include the Concerned module in your class or module and get acces to the meta-info: which concerns are currently included
class FixtureUser
include Concerned
include_concerns :scopes, :validations
include_shared_concerns :caching
end
FixtureUser.my_concerns # => [:scopes, :validations]
FixtureUser.my_shared_concerns # => [:caching]
FixtureUser.all_my_shared_concerns # => [:scopes, :validations, :caching]
You can even include concerns from another scope
class FixtureUserFor
include Concerned
include_concerns :scopes, :validations, for: 'FixtureUser'
include_shared_concerns :caching
end
Will include the FixtureUser::Scopes
and FixtureUser::Validations
into FixtureUserFor
:)
You can use the Concerned.extend_enable!
to let the concern helpers also attempt to extend the host module/class with the ClassMethods module of the concerns module (if such exists). Disable it by using: Concerned.extend_disable!
Use Concerned.extend_enabled?
to see if it is currently enabled or not. By default this feature is turned off.
It is usually better to use ActionSupport::Concern
using extend ActiveSupport::Concern
.
See fx concerns
Copyright (c) 2012 Kristian Mandrup. See LICENSE.txt for further details.