Class: MegaScaffold::KlassDecorator

Inherits:
Object
  • Object
show all
Defined in:
lib/mega_scaffold/klass_decorator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, options) ⇒ KlassDecorator

Returns a new instance of KlassDecorator.



5
6
7
8
# File 'lib/mega_scaffold/klass_decorator.rb', line 5

def initialize(klass, options)
  @klass = klass
  @options = options
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



3
4
5
# File 'lib/mega_scaffold/klass_decorator.rb', line 3

def klass
  @klass
end

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/mega_scaffold/klass_decorator.rb', line 3

def options
  @options
end

Instance Method Details

#decorateObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/mega_scaffold/klass_decorator.rb', line 10

def decorate
  # hack to have local variable available for define_method
  local = options

  klass.singleton_class.define_method :rules do
    {
      except: (Array.wrap(local[:except]) + Array.wrap(local[:ignore])).map(&:to_sym),
      only: (Array.wrap(local[:only]) - Array.wrap(local[:ignore])).map(&:to_sym),
    }
  end

  klass.singleton_class.define_method :fields_config do
    local[:fields].map do |e|
      e.merge({view: Array.wrap(e[:view]).map(&:to_sym)}).deep_symbolize_keys
    end
  end

  klass.singleton_class.define_method :columns_config do
    fields_config.select do |e|
      next true if e[:view].empty?
      next true if e[:view].include?(:index) || e[:view].include?(:all)

      false
    end
  end

  klass.singleton_class.define_method :form_config do
    fields_config.select do |e|
      next false if rules[:except].any? && rules[:except].include?(e[:name].to_sym)
      next false if rules[:only].any? && !rules[:only].include?(e[:name].to_sym)

      next true if e[:view].empty?
      next true if e[:view].include?(:form) || e[:view].include?(:all)
      false
    end
  end

  klass.singleton_class.define_method :show_config do
    fields_config.select do |e|
      next true if e[:view].empty?
      next true if e[:view].include?(:show) || e[:view].include?(:all)

      false
    end
  end      

  klass.singleton_class.define_method :collection_config do
    if local[:collection].is_a?(Proc)
      local[:collection]
    else
      -> (controller) { local[:model].all }
    end
  end

  klass.singleton_class.define_method :parent_config do
    local[:parent]
  end
end