Module: SupportsFeatureMixin

Extended by:
ActiveSupport::Concern
Defined in:
app/models/mixins/supports_feature_mixin.rb

Overview

Including this in a model gives you a DSL to make features supported or not

class Post
  include SupportsFeatureMixin
  supports :publish
  supports_not :fake, :reason => 'We keep it real'
  supports :archive do
    'It is too good' if featured?
  end
end

To make a feature conditionally supported, pass a block to the supports method. The block is evaluated in the context of the instance. If a feature is not supported, return a string for the reason. A nil means it is supported The reason will be accessible through

instance.unsupported_reason(:feature)

Post.supports?(:publish)                     # => true
Post.new.supports?(:publish)                 # => true
Post.supports?(:archive)                     # => true
Post.new(featured: true).supports?(:archive) # => false

To get a reason why a feature is unsupported use the unsupported_reason method

Post.unsupported_reason(:publish)                     # => "Feature not supported"
Post.unsupported_reason(:fake)                        # => "We keep it real"
Post.new(featured: true).unsupported_reason(:archive) # => "It is too good"

If you include this concern in a Module that gets included by the Model you have to extend that model with ActiveSupport::Concern and wrap the supports calls in an included block. This is also true for modules in between!

module Operations
  extend ActiveSupport::Concern
  module Power
    extend ActiveSupport::Concern
    included do
      supports :operation
    end
  end
end

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.default_supports_reasonObject



54
55
56
# File 'app/models/mixins/supports_feature_mixin.rb', line 54

def self.default_supports_reason
  _("Feature not available/supported")
end

Instance Method Details

#supports?(feature) ⇒ Boolean

query the instance if the feature is supported or not

Returns:

  • (Boolean)


64
65
66
# File 'app/models/mixins/supports_feature_mixin.rb', line 64

def supports?(feature)
  !unsupported_reason(feature)
end

#unsupported_reason(feature) ⇒ Object

query instance for the reason why the feature is unsupported



59
60
61
# File 'app/models/mixins/supports_feature_mixin.rb', line 59

def unsupported_reason(feature)
  self.class.unsupported_reason(feature, :instance => self)
end