-
Notifications
You must be signed in to change notification settings - Fork 92
/
view_hints.rb
79 lines (59 loc) · 1.87 KB
/
view_hints.rb
1
2
3
4
5
6
7
8
9
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
68
69
70
71
72
73
74
75
76
77
78
79
module Hobo
class ViewHints
def self.enable
ActiveSupport::Dependencies.load_paths |= ["#{RAILS_ROOT}/app/viewhints"]
end
def self.setter(name, default=nil, &block)
ivname = name.to_s.remove(/\?$/)
metaclass.send :define_method, name do |*args|
if args.empty?
val = instance_variable_get("@#{ivname}")
if val.nil?
val = default.is_a?(Proc) ? instance_eval(&default) : default
instance_variable_set("@#{ivname}", val)
end
val
else
arg = if block
instance_exec(*args, &block)
else
args.first
end
instance_variable_set("@#{ivname}", arg)
end
end
end
setter :model_name, proc { name.sub(/Hints$/, "").titleize }
setter :field_names, {}
setter :field_help, {}
setter :children, proc { model.dependent_collections.sort_by(&:to_s) } do |*args|
args
end
setter :paginate?, proc { !sortable? }
setter :sortable?, proc { defined?(ActiveRecord::Acts::List::InstanceMethods) &&
model < ActiveRecord::Acts::List::InstanceMethods &&
model.new.try.scope_condition == "1 = 1" }
setter :inline_booleans, [] do |*args|
if args[0] == true
model.columns.select { |c| c.type == :boolean }.*.name
else
args.*.to_s
end
end
# Accessors
class << self
def model
@model ||= name.sub(/Hints$/, "").constantize
end
def field_name(field)
field_names.fetch(field.to_sym, field.to_s.titleize)
end
def primary_children
children.first
end
def secondary_children
children.rest
end
end
end
end