class RailsStuff::Statusable::Helper

Class to hold helper methods for statusable field.

Order.has_status_field :status, %i(pending complete)
Order.statuses.list # => %(pending complete)
# ...

Attributes

field[R]
list[R]
model[R]

Public Class Methods

new(model, field, statuses) click to toggle source
# File lib/rails_stuff/statusable/helper.rb, line 11
def initialize(model, field, statuses)
  @model = model
  @field = field.freeze
  @list = statuses.freeze
end

Public Instance Methods

attach(method_name = field.to_s.pluralize) click to toggle source

Generate class method in model to access helper.

# File lib/rails_stuff/statusable/helper.rb, line 31
def attach(method_name = field.to_s.pluralize)
  helper = self
  define_class_method(method_name) { helper }
end
define_class_method(method, &block) click to toggle source
# File lib/rails_stuff/statusable/helper.rb, line 52
def define_class_method(method, &block)
  methods_module::ClassMethods.send(:define_method, method, &block)
end
define_method(method, &block) click to toggle source
# File lib/rails_stuff/statusable/helper.rb, line 48
def define_method(method, &block)
  methods_module.send(:define_method, method, &block)
end
define_scope(name, body) click to toggle source

Rails 4 doesn't use `instance_exec` for scopes, so we do it manually. For Rails 5 it's just use `.scope`.

# File lib/rails_stuff/statusable/helper.rb, line 38
def define_scope(name, body)
  if RailsStuff.rails4?
    model.singleton_class.send(:define_method, name) do |*args|
      all.scoping { instance_exec(*args, &body) } || all
    end
  else
    model.scope(name, body)
  end
end
select_options(only: nil, except: nil) click to toggle source

Returns array compatible with select_options helper.

# File lib/rails_stuff/statusable/helper.rb, line 24
def select_options(only: nil, except: nil)
  only ||= list
  only -= except if except
  only.map { |x| [translate(x), x] }
end
t(status)
Alias for: translate
translate(status) click to toggle source
# File lib/rails_stuff/statusable/helper.rb, line 17
def translate(status)
  model.t(".#{field}_name.#{status}") if status
end
Also aliased as: t

Protected Instance Methods

methods_module() click to toggle source

Module to hold generated methods.

# File lib/rails_stuff/statusable/helper.rb, line 59
def methods_module
  model.statusable_methods
end