Module: RailsStuff::Statusable

Defined in:
lib/rails_stuff/statusable.rb

Overview

Basic helpers to work with ‘status`-like field.

For every status value it provides:

  • scopes with status name (eg. ‘.rejected`, ’.not_rejected’)

  • inquiry method to check status (eg. ‘#rejected?`)

  • bang method to update status (eg. ‘#rejected!`)

It also provides:

  • translation helpers (‘acttivemodel_translation` gem required)

  • inclusion validator

  • string/symbol agnostic ‘#status=`

  • ‘#status_sym`

  • ‘status_select_options` helper.

It supports mapped statuses, just provide a hash with ‘=> interna_value` instead of array of statuses.

Defined Under Namespace

Classes: Builder, MappedBuilder

Instance Method Summary collapse

Instance Method Details

#has_status_field(field = :status, statuses = nil, **options) ⇒ Object

Defines all helpers working with ‘field` (default to `status`). List of values can be given as second argument, otherwise it’ll be read from consts using pluralized name of ‘field` (eg. default to `STATUSES_MAPPING`, `STATUSES`).

#### Options

  • ‘prefix` - used to prefix value-named helpers.

    # this defines #shipped?, #shipped! methods
    has_status_field :delivery_status, i(shipped delivered)
    
    # this defines #delivery_shipped?, #delivery_shipped! methods
    has_status_field :delivery_status, i(shipped delivered), prefix: :delivery_
    
  • ‘suffix` - similar to `prefix`.

  • ‘validate` - additional options for validatior. `false` to disable it.



39
40
41
42
43
44
45
46
47
# File 'lib/rails_stuff/statusable.rb', line 39

def has_status_field(field = :status, statuses = nil, **options)
  unless statuses
    const_name = "#{field.to_s.pluralize.upcase}_MAPPING"
    const_name = field.to_s.pluralize.upcase unless const_defined?(const_name)
    statuses = const_get(const_name)
  end
  generator = statuses.is_a?(Hash) ? MappedBuilder : Builder
  generator.new(self, field, statuses, options).generate
end

#statusable_methodsObject

Module to hold generated methods.



50
51
52
53
54
55
56
57
# File 'lib/rails_stuff/statusable.rb', line 50

def statusable_methods
  # Include generated methods with a module, not right in class.
  @statusable_methods ||= Module.new.tap do |m|
    m.const_set :ClassMethods, Module.new
    include m
    extend m::ClassMethods
  end
end