Module: QueryableArray::DotNotation

Included in:
QueryableArray
Defined in:
lib/queryable_array/dot_notation.rb

Overview

Allows objects to be searched using dot notation thru method_missing which behaves like an alias to QueryableArray::DefaultFinder#[]

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *arguments) ⇒ Object

If method_name does not have a ! or ? suffix then self[/#{method_name}/i] is returned. If it returns nil or raises TypeError (no default_finders) then super is returned.

If method_name ends in a ! then self[method_name] (without the !) is returned. If method_name ends with a ? then a boolean is returned determining whether or not a match was found.

users = QueryableArray.new User.all, :username

users.bob                   # => #<User @username='bob'>
users.BOB                   # => #<User @username='bob'>
users.missing               # => NoMethodError
QueryableArray.new.missing  # => NoMethodError

users.bob!  # => #<User @username='bob'>
users.BOB!  # => NoMethodError

users.bob?      # => true
users.BOB?      # => true
users.missing?  # => false


30
31
32
33
34
35
36
37
38
39
40
# File 'lib/queryable_array/dot_notation.rb', line 30

def method_missing(method_name, *arguments)
  if method_name.to_s =~ /^(.+?)([\!\?])?$/
    search = $2 == '!' ? $1 : /#{$1}/i
    value = begin
      self[search]
    rescue TypeError
      nil
    end
    $2 == '?' ? !!value : (value || super)
  end
end

Class Method Details

.included(base) ⇒ Object



7
8
9
# File 'lib/queryable_array/dot_notation.rb', line 7

def self.included(base)
  base.send :include, DefaultFinder
end

Instance Method Details

#respond_to_missing?(method_name, include_super) ⇒ Boolean

Checks if method_name can be handled by method_missing and and delegates the call to super otherwise.

Returns:

  • (Boolean)


44
45
46
47
48
# File 'lib/queryable_array/dot_notation.rb', line 44

def respond_to_missing?(method_name, include_super)
  !!(method_name.to_s =~ /\?$/ || super || send(method_name))
rescue NoMethodError
  false
end