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



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/supplejack/record.rb', line 135

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