Class: ActiveResourceExtensions::SearchableResource::Search

Inherits:
Object
  • Object
show all
Defined in:
lib/active_resource_extensions/searchable_resource/search.rb

Constant Summary collapse

DEFAULT_PAGE =
1
DEFAULT_PER_PAGE =
10

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, conditions = nil) ⇒ Search

Returns a new instance of Search.



12
13
14
15
# File 'lib/active_resource_extensions/searchable_resource/search.rb', line 12

def initialize model, conditions = nil
  @model = model
  @conditions = conditions || {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object (protected)



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/active_resource_extensions/searchable_resource/search.rb', line 62

def method_missing(name, *args, &block)
  name.to_s =~ /^([\w]*)(=?)$/
  condition_name = $1.to_sym
  operator = $2
  attribute_name = condition_name.to_s.sub(/(#{CONDITIONS_SUFFIXES.join('|')})$/, '').to_sym

  ignore_attribute = ! @model.respond_to?( :is_attribute? )

  if ignore_attribute or @model.is_attribute?( attribute_name )
    if operator == '='
      @conditions[condition_name]= args.first
    else
      @conditions[condition_name]
    end
  else
    super name, *args, &block
  end
end

Instance Attribute Details

#conditionsObject (readonly)

Returns the value of attribute conditions.



10
11
12
# File 'lib/active_resource_extensions/searchable_resource/search.rb', line 10

def conditions
  @conditions
end

Instance Method Details

#allArray<ActiveResource::Base>

Return all records matching conditions.

Returns:

  • (Array<ActiveResource::Base>)

    All records matching conditions.



28
29
30
# File 'lib/active_resource_extensions/searchable_resource/search.rb', line 28

def all
  @model.find( :all, :params => parse_conditions( @conditions ) )
end

#orderObject



17
18
19
# File 'lib/active_resource_extensions/searchable_resource/search.rb', line 17

def order
  @conditions[:order]
end

#order=(new_order) ⇒ Object



21
22
23
# File 'lib/active_resource_extensions/searchable_resource/search.rb', line 21

def order= new_order
  @conditions[:order] = new_order
end

#paginate(pagination_options = {}) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/active_resource_extensions/searchable_resource/search.rb', line 32

def paginate pagination_options = {}
  # Get the parameters corresponding to the search options
  params = parse_conditions @conditions

  total_entries = @model.count params

  # Manage pagination
  params[:page] = ( pagination_options[:page] || DEFAULT_PAGE ).to_i
  params[:per_page] = ( pagination_options[:per_page] || DEFAULT_PER_PAGE ).to_i

  SearchableResource::Collection.new @model.find( :all, :params => params ), params[:page], params[:per_page], total_entries
end