Class: Trophonius::Model

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

Overview

This class will retrieve the records from the FileMaker database and build a RecordSet filled with Record objects. One Record object represents a record in FileMaker.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#all_fieldsObject (readonly)

Contains all the fields on the model (modifiable and non_modifiable)



11
12
13
# File 'lib/trophonius_model.rb', line 11

def all_fields
  @all_fields
end

Class Method Details

.all(sort: {}) ⇒ RecordSet

Retrieve the first 10000000 records from FileMaker from the context of the Model.

Parameters:

  • sort: (Hash) (defaults to: {})

    a hash containing the fields to sort by and the direction to sort in (optional)

Returns:

  • (RecordSet)

    : a RecordSet containing all the Record objects that correspond to the FileMaker records.



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/trophonius_model.rb', line 233

def self.all(sort: {})
  results = Request.retrieve_all(layout_name, sort)
  count = results["response"]["scriptResult"].to_i
  url = URI("http#{Trophonius.config.ssl == true ? "s" : ""}://#{Trophonius.config.host}/fmi/data/v1/databases/#{Trophonius.config.database}/layouts/#{layout_name}/records?_limit=#{count == 0 ? 1000000 : count}")
  results = Request.make_request(url, "Bearer #{Request.get_token}", "get", "{}")
  if results["messages"][0]["code"] != "0"
    Error.throw_error(results["messages"][0]["code"])
  else
    r_results = results["response"]["data"]
    ret_val = RecordSet.new(self.layout_name, self.non_modifiable_fields)
    r_results.each do |r|
      hash = build_result(r)
      ret_val << hash
    end
    ret_val.result_count = count
    return ret_val
  end
end

.build_result(result) ⇒ Record

Builds the resulting Record

Parameters:

  • result: (JSON)

    the HTTP result from FileMaker

Returns:

  • (Record)

    A Record with singleton_methods for the fields where possible



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/trophonius_model.rb', line 146

def self.build_result(result)
  hash = Trophonius::Record.new()
  hash.id = result["recordId"]
  hash.layout_name = layout_name
  result["fieldData"].keys.each do |key|
    # unless key[/\s/] || key[/\W/]
    hash.send(:define_singleton_method, ActiveSupport::Inflector.parameterize(ActiveSupport::Inflector.underscore(key.to_s), separator: '_')) do
      hash[key]
    end
    unless non_modifiable_fields&.include?(key)
      @all_fields.merge!(ActiveSupport::Inflector.parameterize(ActiveSupport::Inflector.underscore(key.to_s), separator: '_').downcase => ActiveSupport::Inflector.parameterize(ActiveSupport::Inflector.underscore(key.to_s), separator: '_'))
      hash.send(:define_singleton_method, "#{ActiveSupport::Inflector.parameterize(ActiveSupport::Inflector.underscore(key.to_s), separator: '_')}=") do |new_val|
        hash[key] = new_val
        hash.modifiable_fields[key] = new_val
        hash.modified_fields[key] = new_val
      end
    end
    # end
    hash.merge!({key => result["fieldData"][key]})
    unless non_modifiable_fields&.include?(key)
      hash.modifiable_fields.merge!({key => result["fieldData"][key]})
    end
  end
  result["portalData"].keys.each do |key|
    unless key[/\s/] || key[/\W/]
      hash.send(:define_singleton_method, ActiveSupport::Inflector.parameterize(ActiveSupport::Inflector.underscore(key.to_s), separator: '_')) do
        hash[key]
      end
    end
    result["portalData"][key].each_with_index do |inner_hash|
      inner_hash.keys.each do |inner_key|
        inner_method = ActiveSupport::Inflector.parameterize(ActiveSupport::Inflector.underscore(inner_key.gsub(/\w+::/, "").to_s), separator: '_')
        unless inner_method[/\s/] || inner_method[/\W/]
          inner_hash.send(:define_singleton_method, inner_method.to_s) { inner_hash[inner_key] }
          inner_hash.send(:define_singleton_method, "id") { inner_hash["recordId"] }
        end
      end
    end
    hash.merge!({key => result["portalData"][key]})
  end
  return hash
end

.config(configuration) ⇒ Object

Sets up the configuration for the model.

Parameters:

  • configuration: (Hash)

    the hash containing the config to setup the model correctly. configuration = “theFileMakerLayoutForThisModel”, non_modifiable_fields: [“an”, “array”, “containing”, “calculation_fields”, “etc.”]



18
19
20
21
22
23
# File 'lib/trophonius_model.rb', line 18

def self.config(configuration)
  @configuration ||= Configuration.new
  @configuration.layout_name = configuration[:layout_name]
  @configuration.non_modifiable_fields = configuration[:non_modifiable_fields]
  @all_fields = {}
end

.create(fieldData) ⇒ Record

Creates and saves a record in FileMaker

Parameters:

  • fieldData: (Hash)

    the fields to fill with the data

Returns:

  • (Record)

    the created record Model.create(fieldOne: “Data”)



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/trophonius_model.rb', line 44

def self.create(fieldData)
  url = URI("http#{Trophonius.config.ssl == true ? "s" : ""}://#{Trophonius.config.host}/fmi/data/v1/databases/#{Trophonius.config.database}/layouts/#{layout_name}/records")
  body = "{\"fieldData\": #{fieldData.to_json}}"
  response = Request.make_request(url, "Bearer #{Request.get_token}", "post", body)
  if response["messages"][0]["code"] != "0"
    Error.throw_error(response["messages"][0]["code"])
  else
    url = URI("http#{Trophonius.config.ssl == true ? "s" : ""}://#{Trophonius.config.host}/fmi/data/v1/databases/#{Trophonius.config.database}/layouts/#{layout_name}/records/#{response["response"]["recordId"]}")
    ret_val = build_result(Request.make_request(url, "Bearer #{Request.get_token}", "get", "{}")["response"]["data"][0])
    ret_val.send(:define_singleton_method, "result_count") do
      1
    end
    return ret_val
  end
end

.delete(record_id) ⇒ Boolean

Deletes a record from FileMaker

Parameters:

  • record_id: (Integer)

    the record id to retrieve from FileMaker

Returns:

  • (Boolean)

    True if the delete was successful



111
112
113
114
115
116
117
118
119
# File 'lib/trophonius_model.rb', line 111

def self.delete(record_id)
  url = URI("http#{Trophonius.config.ssl == true ? "s" : ""}://#{Trophonius.config.host}/fmi/data/v1/databases/#{Trophonius.config.database}/layouts/#{layout_name}/records/#{record_id}")
  response = Request.make_request(url, "Bearer #{Request.get_token}", "delete", "{}")
  if response["messages"][0]["code"] != "0"
    Error.throw_error(response["messages"][0]["code"])
  else
    return true
  end
end

.edit(record_id, fieldData) ⇒ Boolean

Edits a record in FileMaker

Parameters:

  • record_id: (Integer)

    the record id to edit in FileMaker

  • fieldData: (Hash)

    A hash containing the fields to edit and the new data to fill them with

Returns:

  • (Boolean)

    True if the delete was successful



129
130
131
132
133
134
135
136
137
138
# File 'lib/trophonius_model.rb', line 129

def self.edit(record_id, fieldData)
  url = URI("http#{Trophonius.config.ssl == true ? "s" : ""}://#{Trophonius.config.host}/fmi/data/v1/databases/#{Trophonius.config.database}/layouts/#{layout_name}/records/#{record_id}")
  body = "{\"fieldData\": #{fieldData.to_json}}"
  response = Request.make_request(url, "Bearer #{Request.get_token}", "patch", body)
  if response["messages"][0]["code"] != "0"
    Error.throw_error(response["messages"][0]["code"])
  else
    true
  end
end

.find(record_id) ⇒ Record

Finds and returns a Record corresponding to the record_id

Parameters:

  • record_id: (Integer)

    the record id to retrieve from FileMaker

Returns:



91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/trophonius_model.rb', line 91

def self.find(record_id)
  url = URI("http#{Trophonius.config.ssl == true ? "s" : ""}://#{Trophonius.config.host}/fmi/data/v1/databases/#{Trophonius.config.database}/layouts/#{layout_name}/records/#{record_id}")
  response = Request.make_request(url, "Bearer #{Request.get_token}", "get", "{}")
  if response["messages"][0]["code"] != "0"
    Error.throw_error(response["messages"][0]["code"], record_id)
  else
    ret_val = build_result(response["response"]["data"][0])
    ret_val.send(:define_singleton_method, "result_count") do
      1
    end
    return ret_val
  end
end

.firstRecord

Retrieve the first record from FileMaker from the context of the Model.

Returns:

  • (Record)

    : a Record corresponding to the FileMaker record.



193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/trophonius_model.rb', line 193

def self.first
  results = Request.retrieve_first(layout_name)
  if results["messages"][0]["code"] != "0"
    Error.throw_error(results["messages"][0]["code"])
  else
    r_results = results["response"]["data"]
    ret_val = r_results.empty? ? Trophonius::Record.new({}) : build_result(r_results[0])
    ret_val.send(:define_singleton_method, "result_count") do
      r_results.empty? ? 0 : 1
    end
    return ret_val
  end
end

.layout_nameObject

Returns the FileMaker layout this Model corresponds to



27
28
29
# File 'lib/trophonius_model.rb', line 27

def self.layout_name
  @configuration.layout_name
end

.non_modifiable_fieldsObject

Returns the fields that FileMaker won’t allow us to modify



33
34
35
# File 'lib/trophonius_model.rb', line 33

def self.non_modifiable_fields
  @configuration.non_modifiable_fields
end

.run_script(script: "", scriptparameter: "") ⇒ String

Runs a FileMaker script from the context of the Model.

Parameters:

  • script: (String) (defaults to: "")

    the FileMaker script to run

  • scriptparameter: (String) (defaults to: "")

    the parameter required by the FileMaker script

Returns:

  • (String)

    : string representing the script result returned by FileMaker



215
216
217
218
219
220
221
222
223
224
225
# File 'lib/trophonius_model.rb', line 215

def self.run_script(script: "", scriptparameter: "")
  result = Request.run_script(script, scriptparameter, layout_name)
  if result["messages"][0]["code"] != "0"
    Error.throw_error(result["messages"][0]["code"])
  elsif result["response"]["scriptResult"] == "403"
    Error.throw_error(403)
  else
    ret_val = result["response"]["scriptResult"]
    return ret_val
  end
end

.where(fieldData) ⇒ RecordSet

Finds and returns a RecordSet containing the records fitting the find request

Parameters:

  • fieldData: (Hash)

    the data to find

Returns:

  • (RecordSet)

    a RecordSet containing all the Record objects that correspond to FileMaker records fitting the find request Model.where(fieldOne: “Data”)



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/trophonius_model.rb', line 67

def self.where(fieldData)
  url = URI("http#{Trophonius.config.ssl == true ? "s" : ""}://#{Trophonius.config.host}/fmi/data/v1/databases/#{Trophonius.config.database}/layouts/#{self.layout_name}/_find")
  body = "{\"query\": [#{fieldData.to_json}]}"
  response = Request.make_request(url, "Bearer #{Request.get_token}", "post", body)
  if response["messages"][0]["code"] != "0"
    return RecordSet.new(self.layout_name, self.non_modifiable_fields) if response["messages"][0]["code"] == "101" || response["messages"][0]["code"] == "401"
    Error.throw_error(response["messages"][0]["code"])
  else
    r_results = response["response"]["data"]
    ret_val = RecordSet.new(self.layout_name, self.non_modifiable_fields)
    r_results.each do |r|
      hash = build_result(r)
      ret_val << hash
    end
    return ret_val
  end
end