ivan
ivan

Reputation: 6322

Modularizing class-level method calls by evaluating them in `included` methods

I'm working with a Rails project that uses the flip gem for feature flags. We have a Feature class in which you can declare the various feature flags you want to use,

# app/models/feature.rb

class Feature < ActiveRecord::Base
  extend   Flip::Declarable
  strategy Flip::DeclarationStrategy

  feature :ivans_feature_A
  feature :ivans_feature_B
  feature :ivans_feature_C

  feature :kramers_feature_X
  feature :kramers_feature_X
end

As the project grows, so does the number of feature-flags we've got declared in this file. A coworker suggested we break related feature-declarations into separate modules to organize things.

I've found a way to do this, but it's not a pattern I've seen used before so I wonder if there's a more standard way. I'm defining namespaced modules for each bunch of features I want to group together:

app/models/features/ivans_features.rb

module Features::IvansFeatures
  def self.included(base)
    base.feature :ivans_feature_A
    base.feature :ivans_feature_B
    base.feature :ivans_feature_C
  end
end

app/models/features/kramers_features.rb

module Features::KramersFeatures
  def self.included(base)
    base.feature :kramers_feature_X
    base.feature :kramers_feature_Y
  end
end

...and including them in the feature model:

# app/models/feature.rb

class Feature < ActiveRecord::Base
  extend   Flip::Declarable
  strategy Flip::DeclarationStrategy

  include  Features::IvansFeatures
  include  Features::KramersFeatures
end

Is it strange to mix a module into a class for the sole purpose of usingthe included callback to run some method calls on the class?

Upvotes: 0

Views: 33

Answers (1)

CWitty
CWitty

Reputation: 4536

In your Feature class you can extend ActiveSupport::Concern and then do something like

included do
  feature :kramers_feature_X
end

Upvotes: 1

Related Questions