Class: Sakuramochi::Predicate

Inherits:
Object
  • Object
show all
Defined in:
lib/sakuramochi/predicate.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Predicate

Returns a new instance of Predicate.



5
6
7
8
9
10
11
12
# File 'lib/sakuramochi/predicate.rb', line 5

def initialize(options = {}) 
  options = options.reverse_merge(:expand => true)
  @name = options[:name]
  @arel_predicate = options[:arel_predicate]
  @expand = options[:expand]
  @converter = options[:converter]
  @validator = options[:validator] || proc { |v| v.respond_to?(:empty?) ? !v.empty? : !v.nil? }
end

Instance Attribute Details

#arel_predicateObject (readonly)

Returns the value of attribute arel_predicate.



3
4
5
# File 'lib/sakuramochi/predicate.rb', line 3

def arel_predicate
  @arel_predicate
end

#converterObject (readonly)

Returns the value of attribute converter.



3
4
5
# File 'lib/sakuramochi/predicate.rb', line 3

def converter
  @converter
end

#expandObject (readonly)

Returns the value of attribute expand.



3
4
5
# File 'lib/sakuramochi/predicate.rb', line 3

def expand
  @expand
end

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/sakuramochi/predicate.rb', line 3

def name
  @name
end

#validatorObject (readonly)

Returns the value of attribute validator.



3
4
5
# File 'lib/sakuramochi/predicate.rb', line 3

def validator
  @validator
end

Class Method Details

.detect(attr) ⇒ Object



39
40
41
42
43
# File 'lib/sakuramochi/predicate.rb', line 39

def self.detect(attr)
  attr_name = attr.to_s.dup
  pred_name = names_by_decreasing_length.detect {|p| attr_name.sub!(/_#{p}$/, '')}
  [attr_name, Sakuramochi.config.predicates[pred_name]]
end

.namesObject



31
32
33
# File 'lib/sakuramochi/predicate.rb', line 31

def self.names
  Sakuramochi.config.predicates.keys
end

.names_by_decreasing_lengthObject



35
36
37
# File 'lib/sakuramochi/predicate.rb', line 35

def self.names_by_decreasing_length
  names.sort { |a, b| b.length <=> a.length }
end

Instance Method Details

#convert(value) ⇒ Object



14
15
16
17
18
19
20
21
# File 'lib/sakuramochi/predicate.rb', line 14

def convert(value)
  return value unless @converter
  if @expand
    Array(value).map { |v| @converter.call(v) }
  else
    @converter.call(value)
  end
end

#validate(value) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/sakuramochi/predicate.rb', line 23

def validate(value)
  if @expand
    Array(value).select { |v| @validator.call(v) }.any?
  else
    @validator.call(value)
  end
end