Module: Supplejack::Record::ClassMethods

Defined in:
lib/supplejack/record.rb

Instance Method Summary collapse

Instance Method Details

#find(id_or_array, options = {}) ⇒ Supplejack::Record

Finds a record or array of records from the Supplejack API

Returns:

  • (Supplejack::Record)

    A record or array of records initialized with the class of where the Supplejack::Record module was included



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/supplejack/record.rb', line 110

def find(id_or_array, options={})
  if id_or_array.is_a?(Array)
    options = {:record_ids => id_or_array, :fields => Supplejack.fields.join(',') }
    response = get("/records/multiple", options)
    response["records"].map {|attributes| new(attributes) }
  else
    begin
      # handle malformed id's before requesting anything. 
      id = id_or_array.to_i
      raise(Supplejack::MalformedRequest, "'#{id_or_array}' is not a valid record id") if id <= 0

      # Do not send any parameters in the :search key when the user didn't specify any options
      # And also always send the :fields parameter
      #
      search_klass = Supplejack::Search
      search_klass = Supplejack.search_klass.classify.constantize if Supplejack.search_klass.present?

      any_options = options.try(:any?)

      search = search_klass.new(options)
      search_options = search.api_params
      search_options = search.merge_extra_filters(search_options)

      options = {:search => search_options}
      options[:fields] = options[:search].delete(:fields)
      options.delete(:search) unless any_options

      response = get("/records/#{id}", options)
      new(response['record'])
    rescue RestClient::ResourceNotFound => e
      raise Supplejack::RecordNotFound, "Record with ID #{id_or_array} was not found"
    end
  end
end