local_model 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d1f1bc15ddc521bde62f5f54c0a2d1afd83fce6cb48f6d219a2f51ab10bcca5a
4
+ data.tar.gz: 68bba359571444d2642144a08f8048eaa6dc0576968a92a896dc8e52b1258f49
5
+ SHA512:
6
+ metadata.gz: 9ad5e42e5270c50e4e05d8ef678fb59885efd9fbd15acbd5e2ce76c4f47ad46ab63e8aef0259257db6fa36b510853bf78e72c097d2319a5a6ab33ecd2dfdbe81
7
+ data.tar.gz: d43a6e529cd6670cbbac2711db14af646d68f0fb40616d86c0347d9491f4acf7d3063ab0fca191f42cf1848cca1801d87d87d7b0347695abcaace0a143dad347
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.3
7
+ before_install: gem install bundler -v 1.17.2
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at micah.shute@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in local_model.gemspec
6
+ gemspec
7
+
8
+ gem "require_all", "~> 3.0"
9
+
10
+ gem "pry", "~> 0.14.1", group: :development
11
+
12
+ gem "irb", "~> 1.3"
data/Gemfile.lock ADDED
@@ -0,0 +1,49 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ local_model (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ coderay (1.1.3)
10
+ diff-lcs (1.4.4)
11
+ io-console (0.5.9)
12
+ irb (1.3.5)
13
+ reline (>= 0.1.5)
14
+ method_source (1.0.0)
15
+ pry (0.14.1)
16
+ coderay (~> 1.1)
17
+ method_source (~> 1.0)
18
+ rake (13.0.3)
19
+ reline (0.2.5)
20
+ io-console (~> 0.5)
21
+ require_all (3.0.0)
22
+ rspec (3.10.0)
23
+ rspec-core (~> 3.10.0)
24
+ rspec-expectations (~> 3.10.0)
25
+ rspec-mocks (~> 3.10.0)
26
+ rspec-core (3.10.1)
27
+ rspec-support (~> 3.10.0)
28
+ rspec-expectations (3.10.1)
29
+ diff-lcs (>= 1.2.0, < 2.0)
30
+ rspec-support (~> 3.10.0)
31
+ rspec-mocks (3.10.2)
32
+ diff-lcs (>= 1.2.0, < 2.0)
33
+ rspec-support (~> 3.10.0)
34
+ rspec-support (3.10.2)
35
+
36
+ PLATFORMS
37
+ x86_64-linux
38
+
39
+ DEPENDENCIES
40
+ bundler (~> 2.2)
41
+ irb (~> 1.3)
42
+ local_model!
43
+ pry (~> 0.14.1)
44
+ rake (~> 13.0)
45
+ require_all (~> 3.0)
46
+ rspec (~> 3.10)
47
+
48
+ BUNDLED WITH
49
+ 2.2.17
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Micah Shute
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,103 @@
1
+ # LocalModel
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/local_model`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'local_model'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install local_model
22
+
23
+ ## Usage
24
+
25
+ Create your schema:
26
+
27
+ ```rb
28
+ # Some config file
29
+
30
+ LocalModel.config |c|
31
+ c.path = "/some/path/you_want/to_store/the_csv_files"
32
+ end
33
+ ```
34
+
35
+ ```rb
36
+ # User.rb
37
+
38
+ class User < LocalModel::CSV
39
+
40
+ schema do |t|
41
+ t.string :name
42
+ t.integer :age
43
+ t.string :password
44
+ end
45
+
46
+ has_many :dogs
47
+
48
+ end
49
+ ```
50
+ ```rb
51
+ # Dog.rb
52
+
53
+ class Dog < LocalModel::CSV
54
+
55
+ schema do |t|
56
+ t.string :name
57
+ t.integer :age
58
+ t.integer :user_id
59
+ end
60
+
61
+ belongs_to :user
62
+ end
63
+
64
+ ```
65
+
66
+ ...then
67
+
68
+ ```rb
69
+
70
+ u = User.create(name: "Cyrus Harding", age: 45, password: "LincolnIsland")
71
+ d = Dog.create(name: "Top", age: 3, user: u)
72
+
73
+ u.dogs # => [#<Dog:0x00005568e92b3f48 @age=3, @id=1, @name="Top">]
74
+ d.user # => #<User:0x00005568e92b3f48 @age=45, @id=1, @name="Cyrus Harding", @password="LincolnIsland">
75
+
76
+ u == User.first # true
77
+ Dog.where(user: u).first == d # true
78
+
79
+ ```
80
+ As of now, supports:
81
+ - #destroy, .find, .create, .new, .where, .first, .second, .last, relationships, updating,
82
+
83
+ Does not support yet (notably):
84
+ - .build, .update, validations, #<< to add many relationships
85
+ - object equivalence if gotten from source twice
86
+
87
+ ## Development
88
+
89
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
90
+
91
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
92
+
93
+ ## Contributing
94
+
95
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/local_model. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
96
+
97
+ ## License
98
+
99
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
100
+
101
+ ## Code of Conduct
102
+
103
+ Everyone interacting in the LocalModel project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/local_model/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,13 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
7
+
8
+ desc "run a console"
9
+ task :console do
10
+ require 'pry'
11
+ require_relative './lib/local_model.rb'
12
+ binding.pry
13
+ end
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "local_model"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,49 @@
1
+ require 'pry'
2
+ require_relative "./local_model/version"
3
+ require 'csv'
4
+ require 'require_all'
5
+ require_relative './local_model/adapters/boolean_adapter'
6
+ require_relative './local_model/adapters/datetime_adapter'
7
+ require_relative './local_model/adapters/float_adapter'
8
+ require_relative './local_model/adapters/integer_adapter'
9
+ require_relative './local_model/adapters/string_adapter'
10
+ require_relative './local_model/concerns/csv_interactable'
11
+ require_relative './local_model/helpers/functions'
12
+ require_relative './local_model/helpers/pluralized_words'
13
+ require_relative './local_model/model'
14
+ require_relative './local_model/csv'
15
+
16
+ module LocalModel
17
+ class Error < StandardError; end
18
+
19
+ @@path = "#{Dir.pwd}/tmp"
20
+
21
+ def self.path
22
+ @@path
23
+ end
24
+
25
+ def self.config(&block)
26
+ configuration = Configuration.new
27
+ if block_given?
28
+ yield(configuration)
29
+ end
30
+ @@path = configuration.path
31
+ Dir.mkdir(configuration.path) unless Dir.exist?(configuration.path)
32
+ if configuration.cleanup_on_start
33
+ Dir.foreach do |f|
34
+ fn = File.join(configuration.path, f)
35
+ File.delete(fn) if f != '.' && f != '..'
36
+ end
37
+ end
38
+ end
39
+
40
+ class Configuration
41
+
42
+ attr_accessor :path, :cleanup_on_start
43
+
44
+ def initialize
45
+ @path = "#{Dir.pwd}/tmp"
46
+ @cleanup_on_start = false
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,11 @@
1
+ class LocalModel::BooleanAdapter
2
+
3
+ def self.write(bool)
4
+ bool.to_s
5
+ end
6
+
7
+ def self.read(boolstr)
8
+ boolstr == "true"
9
+ end
10
+
11
+ end
@@ -0,0 +1,11 @@
1
+ class LocalModel::DatetimeAdapter
2
+
3
+ def self.write(dt)
4
+ dt.to_i.to_s
5
+ end
6
+
7
+ def self.read(dtstr)
8
+ return nil if dtstr == 'nil' || dtstr.to_i == 0
9
+ Time.at(dtstr.to_i)
10
+ end
11
+ end
@@ -0,0 +1,11 @@
1
+ class LocalModel::FloatAdapter
2
+
3
+ def self.write(fl)
4
+ "#{fl}"
5
+ end
6
+
7
+ def self.read(flstr)
8
+ flstr =~ /[^0-9\.]/ ? nil : flstr.to_f
9
+ end
10
+
11
+ end
@@ -0,0 +1,12 @@
1
+ class LocalModel::IntegerAdapter
2
+
3
+ def self.write(int)
4
+ "#{int}"
5
+ end
6
+
7
+ def self.read(intstr)
8
+ return nil if intstr != '0' && intstr.to_i == 0
9
+ intstr.to_i
10
+ end
11
+
12
+ end
@@ -0,0 +1,12 @@
1
+ class LocalModel::StringAdapter
2
+
3
+
4
+ def self.write(str)
5
+ str.to_s
6
+ end
7
+
8
+ def self.read(str)
9
+ str == 'nil' ? nil : str
10
+ end
11
+
12
+ end
@@ -0,0 +1,223 @@
1
+ module CSVInteractable
2
+
3
+ module ClassMethods
4
+
5
+ @@rand = Random.new
6
+
7
+ def write_headers
8
+ CSV.open(self.storage_path, 'wb') do |csv|
9
+ csv << columns.map(&:to_s)
10
+ end
11
+ end
12
+
13
+ def mutate_csv(option=:mutate,&block)
14
+ while File.exist?("#{self.storage_path}.bak.csv")
15
+ r = @@rand.rand / 10.0
16
+ sleep(r)
17
+ end
18
+ rand_val = @@rand.rand(1000000)
19
+ f = File.new("#{self.storage_path}-#{rand_val}.prep", 'w')
20
+ f.close
21
+ r = @@rand.rand / 10.0
22
+ sleep(r)
23
+
24
+ if File.exist?("#{self.storage_path}.bak.csv") || Dir["#{self.storage_path}-*.prep"].length > 1
25
+ File.delete("#{self.storage_path}-#{rand_val}.prep")
26
+ if @@rand.rand(2) == 1
27
+ sleep(0.5)
28
+ end
29
+ mutate_csv
30
+ return
31
+ else
32
+ File.delete("#{self.storage_path}-#{rand_val}.prep")
33
+ last_id = 0
34
+ CSV.open("#{self.storage_path}.bak.csv", 'wb', headers: self.get_schema.keys.map(&:to_s), write_headers: true, header_converters: [:symbol, :downcase]) do |csv_bak|
35
+ CSV.open(self.storage_path, 'r', headers: true, header_converters: [:symbol, :downcase]) do |csv_orig|
36
+ csv_orig.each do |row|
37
+ csv_bak << row
38
+ last_id = get_adapter(:integer).read(row[:id])
39
+ end
40
+ end
41
+ end
42
+ if option == :mutate
43
+ CSV.open("#{self.storage_path}.bak.csv", 'r', headers: true, header_converters: [:symbol, :downcase]) do |csv_bak|
44
+ CSV.open(self.storage_path, 'w', headers: self.get_schema.keys.map(&:to_s), write_headers: true, header_converters: [:symbol, :downcase]) do |csv_orig|
45
+ csv_bak.each do |bak_row|
46
+ prep_row_read!(bak_row)
47
+ yield(csv_orig, bak_row)
48
+ end
49
+ end
50
+ end
51
+ else
52
+ CSV.open(self.storage_path, 'a', headers: true, header_converters: [:symbol, :downcase]) do |csv|
53
+ yield(csv, last_id)
54
+ end
55
+ end
56
+ File.delete("#{self.storage_path}.bak.csv")
57
+ end
58
+ end
59
+
60
+ def read_from_record(row)
61
+ row = row.to_h
62
+ row.reduce({}) do |mem, (k,v)|
63
+ data_type = self.get_schema[k]
64
+ adapter = get_adapter[data_type]
65
+ mem[k] = adapter.read(v)
66
+ end
67
+ end
68
+
69
+ def new_from_record(row)
70
+ formatted_hash = read_from_record(row)
71
+ inst = self.new(**formatted_hash)
72
+ inst.id = formatted_hash[:id]
73
+ inst
74
+ end
75
+
76
+ def get_adapter(data_type)
77
+ case data_type
78
+ when :integer
79
+ LocalModel::IntegerAdapter
80
+ when :boolean
81
+ LocalModel::BooleanAdapter
82
+ when :float
83
+ LocalModel::FloatAdapter
84
+ when :datetime
85
+ LocalModel::DatetimeAdapter
86
+ when :string
87
+ LocalModel::StringAdapter
88
+ else
89
+ raise ArgumentError.new("Incorrect datatype entered (#{data_type})")
90
+ end
91
+ end
92
+
93
+ def prep_row_read!(row)
94
+ row_hash = row.to_h
95
+ row_hash.each do |k,v|
96
+ data_type = get_schema[k]
97
+ adapter = get_adapter(data_type)
98
+ row[k] = adapter.read(v)
99
+ end
100
+ row
101
+ end
102
+
103
+ def prep_row_write!(row)
104
+ row_hash = row.to_h
105
+ row_hash.each do |k,v|
106
+ data_type = get_schema[k]
107
+ adapter = get_adapter(data_type)
108
+ row[k] = adapter.write(v)
109
+ end
110
+ row
111
+ end
112
+
113
+ def find_record(mode: 'r', &block)
114
+ CSV.open(self.storage_path, mode, headers: true, header_converters: [:symbol, :downcase]) do |csv|
115
+ csv.each do |row|
116
+ prep_row_read!(row)
117
+ return row if yield(row)
118
+ end
119
+ return nil
120
+ end
121
+ end
122
+
123
+ def each_record(mode: 'r', &block)
124
+ CSV.open(self.storage_path, mode, headers: true, header_converters: [:symbol, :downcase]) do |csv|
125
+ csv.each do |row|
126
+ prep_row_read!(row)
127
+ yield(row)
128
+ end
129
+ end
130
+ end
131
+
132
+ def all_records(mode: 'r', &block)
133
+ records = []
134
+ CSV.open(self.storage_path, mode, headers: true, header_converters: [:symbol, :downcase]) do |csv|
135
+ csv.each do |row|
136
+ prep_row_read!(row)
137
+ records << row if yield(row)
138
+ end
139
+ end
140
+ records
141
+ end
142
+
143
+ def append_row(data, should_add_id: true)
144
+ row = data.reduce(CSV::Row.new([],[])) do |mem, (k,v)|
145
+ data_type = get_schema[k]
146
+ adapter = get_adapter(data_type)
147
+ mem[k] = adapter.write(v)
148
+ mem
149
+ end
150
+ begin
151
+ ret_val = nil
152
+ self.mutate_csv(:append) do |csv, last_id|
153
+ if should_add_id
154
+ ret_val = last_id + 1
155
+ row[:id] = get_adapter(:integer).write(last_id + 1)
156
+ end
157
+ csv << row
158
+ end
159
+ ret_val
160
+ rescue => e
161
+ File.delete("#{self.storage_path}.bak.csv") if File.exist?("#{self.storage_path}.bak.csv")
162
+ raise e
163
+ false
164
+ end
165
+ end
166
+
167
+ def mutate_row(data)
168
+ begin
169
+ self.mutate_csv(:mutate) do |csv, bak_row|
170
+ if bak_row[:id] == data[:id]
171
+ data.each do |k,v|
172
+ bak_row[k] = data[k]
173
+ end
174
+ prep_row_write!(bak_row)
175
+ csv << bak_row
176
+ else
177
+ prep_row_write!(bak_row)
178
+ csv << bak_row
179
+ end
180
+ end
181
+ true
182
+ rescue => e
183
+ File.delete("#{self.storage_path}.bak.csv")
184
+ false
185
+ end
186
+ end
187
+
188
+ def delete_row(data)
189
+ begin
190
+ self.mutate_csv(:mutate) do |csv, bak_row|
191
+ if bak_row[:id] != data[:id]
192
+ prep_row_write!(bak_row)
193
+ csv << bak_row
194
+ end
195
+ end
196
+ true
197
+ rescue
198
+ File.delete("#{self.storage_path}.bak.csv")
199
+ false
200
+ end
201
+ end
202
+
203
+ end
204
+
205
+ module InstanceMethods
206
+ def save
207
+ model_schema = self.class.get_schema
208
+ self_data = model_schema.reduce({}) do |mem, (k,v)|
209
+ mem[k] = self.send(k)
210
+ mem
211
+ end
212
+ if self.id.nil?
213
+ id = self.class.append_row(self_data)
214
+ self.id = id
215
+ !!id
216
+ else
217
+ return self.class.mutate_row(self_data)
218
+ end
219
+ end
220
+
221
+ end
222
+
223
+ end
@@ -0,0 +1,129 @@
1
+ class LocalModel::CSV < LocalModel::Model
2
+
3
+ extend CSVInteractable::ClassMethods
4
+ include CSVInteractable::InstanceMethods
5
+
6
+ def self.schema(&block)
7
+ builder = SchemaBuilder.new(self)
8
+ yield builder
9
+
10
+ schema_dict = builder.schema.dup
11
+ self.define_method :get_schema do
12
+ schema_dict
13
+ end
14
+
15
+ self.define_singleton_method :get_schema do
16
+ schema_dict
17
+ end
18
+
19
+ cols = builder.schema.keys.dup
20
+ self.define_method :columns do
21
+ cols
22
+ end
23
+
24
+ self.define_singleton_method :columns do
25
+ cols
26
+ end
27
+
28
+ schema_data = cols.each_with_index.reduce({}) do |mem, (key,i)|
29
+ mem[key] = {}
30
+ mem[key][:adapter] = get_adapter(schema_dict[key])
31
+ mem[key][:type] = schema_dict[key]
32
+ mem[key][:column_number] = i
33
+ mem
34
+ end
35
+
36
+ self.define_method :schema_data do
37
+ schema_data
38
+ end
39
+
40
+ if !File.file?(self.storage_path)
41
+ CSV.open(self.storage_path, 'wb') do |csv|
42
+ csv << cols.map(&:to_s)
43
+ end
44
+ end
45
+ end
46
+
47
+ def self.all
48
+ all_instances = []
49
+ each_record do |row|
50
+ all_instances << new_from_record(row)
51
+ end
52
+ all_instances
53
+ end
54
+
55
+ def self.destroy_all
56
+ self.all.each{ |obj| obj.destroy }
57
+ end
58
+
59
+ def self.where(**args)
60
+ all_records do |row|
61
+ found = true
62
+ args.each do |k,v|
63
+ if row[k] != v
64
+ found = false
65
+ break
66
+ end
67
+ end
68
+ found
69
+ end.map{|r| new_from_record(r) }
70
+ end
71
+
72
+ def self.find_by(**args)
73
+ found_record = find_record do |row|
74
+ matched = true
75
+ args.each do |k,v|
76
+ if row[k] != v
77
+ matched = false
78
+ break
79
+ end
80
+ end
81
+ return new_from_record(row) if matched
82
+ end
83
+ nil
84
+ end
85
+
86
+ def self.first
87
+ all.first
88
+ end
89
+
90
+ def self.second
91
+ all[1]
92
+ end
93
+
94
+ def self.last
95
+ all.last
96
+ end
97
+
98
+ def self.new_from_record(row)
99
+ obj = new(**row.to_h)
100
+ obj.id = row[:id]
101
+ obj
102
+ end
103
+
104
+ def self.find(id)
105
+ return self.find_by(id: id)
106
+ end
107
+
108
+ def self.create(**args)
109
+ inst = new(**args)
110
+ inst.save
111
+ inst
112
+ end
113
+
114
+ def initialize(**args)
115
+ args.each do |k,v|
116
+ self.send("#{k}=", v)
117
+ end
118
+ self.id = nil
119
+ end
120
+
121
+ def saved?
122
+ !self.id.nil?
123
+ end
124
+
125
+ def destroy
126
+ self.class.delete_row({id: self.id})
127
+ end
128
+
129
+ end
@@ -0,0 +1,56 @@
1
+ class LocalModel::Functions
2
+
3
+ def self.snake_to_camel(snakecase)
4
+ snakecase.to_s.split("_").map.with_index do |word, i|
5
+ i == 0 ? word : word.capitalize
6
+ end.join('')
7
+ end
8
+
9
+ def self.camel_to_snake(camel)
10
+ camel.to_s.split(/(?=[A-Z])/).map(&:downcase).join("_")
11
+ end
12
+
13
+ def self.singularize(word)
14
+ return PluralizedWords::IRREGULAR_SINGULARIZED_WORDS[word] if PluralizedWords::IRREGULAR_PLURALIZED_WORDS[word]
15
+ if word[-1] == "i"
16
+ "#{word[0...-1]}us"
17
+ elsif word[-1] == "a"
18
+ "#{word[0..-1]}on"
19
+ elsif word =~ /ies$/
20
+ "#{word[0...-3]}y"
21
+ elsif word =~ /es$/
22
+ if word[-3] == "v"
23
+ word[-3] = "f"
24
+ word[0...-2]
25
+ elsif word[0...-2] =~ /s$|ss$|sh$|ch$|x$|z$|o$/
26
+ word[0...-2]
27
+ else
28
+ "#{word[0...-1]}"
29
+ end
30
+ else
31
+ "#{word[0...-1]}"
32
+ end
33
+ end
34
+
35
+ def self.pluralize(word)
36
+ return PluralizedWords::IRREGULAR_PLURALIZED_WORDS[word] if PluralizedWords::IRREGULAR_PLURALIZED_WORDS[word]
37
+ if word[-2..-1] == "us"
38
+ "#{word[0...-2]}i"
39
+ elsif word[-2..-1] == "on"
40
+ "#{word[0...-2]}a"
41
+ elsif word =~ /s$|ss$|sh$|ch$|x$|z$|o$/
42
+ "#{word}es"
43
+ elsif word =~ /f$|fe$/
44
+ word[-1] == "f" ? word[-1] = "v" : word[-2] = "v"
45
+ word[-1] == "e" ? "#{word}s" : "#{word}es"
46
+ elsif word =~ /[^aeiou]y$/
47
+ "#{word[0...-1]}ies"
48
+ elsif word[-2..-1] == "is"
49
+ "#{word[0...-2]}es"
50
+ else
51
+ "#{word}s"
52
+ end
53
+ end
54
+
55
+
56
+ end
@@ -0,0 +1,49 @@
1
+ class PluralizedWords
2
+
3
+ IRREGULAR_SINGULARIZED_WORDS = {
4
+ "children" => "child",
5
+ "geese" => "goose",
6
+ "men" => "man",
7
+ "women" => "woman",
8
+ "teeth" => "tooth",
9
+ "feet" => "foot",
10
+ "mice" => "mouse",
11
+ "people" => "person",
12
+ "sheep" => "sheep",
13
+ "series" => "series",
14
+ "species" => "species",
15
+ "deer" => "deer",
16
+ "photos" => "photo",
17
+ "pianos" => "piano",
18
+ "halos" => "halo",
19
+ "roofs" => "roof",
20
+ "beliefs" => "belief",
21
+ "chefs" => "chef",
22
+ "chiefs" => "chief",
23
+ "gasses" => "gas"
24
+ }
25
+
26
+ IRREGULAR_PLURALIZED_WORDS = {
27
+ "child" => "children",
28
+ "goose" => "geese",
29
+ "man" => "men",
30
+ "woman" => "women",
31
+ "tooth" => "teeth",
32
+ "foot" => "feet",
33
+ "mouse" => "mice",
34
+ "person" => "people",
35
+ "sheep" => "sheep",
36
+ "series" => "series",
37
+ "species" => "species",
38
+ "deer" => "deer",
39
+ "photo" => "photos",
40
+ "piamo" => "pianos",
41
+ "halo" => "halos",
42
+ "roof" => "roofs",
43
+ "belief" => "beliefs",
44
+ "chef" => "chefs",
45
+ "chief" => "chiefs",
46
+ "gas" => "gasses"
47
+ }
48
+
49
+ end
@@ -0,0 +1,82 @@
1
+ class LocalModel::Model
2
+
3
+ def self.schema(&block)
4
+ raise NoMethodError.new("self.schema must be defined")
5
+ # yield(SchemaBuilder.new(self))
6
+ end
7
+
8
+ def self.belongs_to(association)
9
+ define_method association do
10
+ id = self.send("#{association}_id")
11
+ association_class_name = LocalModel::Functions.snake_to_camel(association).capitalize
12
+ association_class = Object.const_get(association_class_name)
13
+ association_class.find(id)
14
+ end
15
+
16
+ define_method "#{association}=" do |association_obj|
17
+ self.send("#{association}_id=", association_obj.id)
18
+ end
19
+ end
20
+
21
+ def self.has_many(association)
22
+ association_portions = association.to_s.split('_')
23
+ association_portions_last = association_portions.last
24
+ singular_association_last = LocalModel::Functions.singularize(association_portions_last)
25
+ singularized_association = association_portions[0...-1] + [singular_association_last]
26
+ singularized_snakecase = singularized_association.join('_')
27
+ association_classname = LocalModel::Functions.snake_to_camel(singularized_snakecase).capitalize
28
+ current_class_id_methodname = "#{LocalModel::Functions.camel_to_snake(self.to_s)}_id"
29
+ belongs_to_id_sym = current_class_id_methodname.to_sym
30
+
31
+ define_method association do
32
+ association_class = Object.const_get(association_classname)
33
+ association_class.where(belongs_to_id_sym => self.id)
34
+ end
35
+
36
+
37
+ end
38
+
39
+
40
+ def self.storage_path
41
+ slash = LocalModel.path == '/' ? '' : '/'
42
+ "#{LocalModel.path}#{slash}#{self}.csv"
43
+ end
44
+
45
+
46
+ class SchemaBuilder
47
+
48
+ attr_reader :schema
49
+
50
+ def initialize(model)
51
+ @model = model
52
+ @schema = { id: :integer }
53
+ @model.attr_accessor :id
54
+ end
55
+
56
+ def string(name)
57
+ @model.attr_accessor name
58
+ @schema[name] = :string
59
+ end
60
+
61
+ def integer(name)
62
+ @model.attr_accessor name
63
+ @schema[name] = :integer
64
+ end
65
+
66
+ def boolean(name)
67
+ @model.attr_accessor name
68
+ @schema[name] = :boolean
69
+ end
70
+
71
+ def float(name)
72
+ @model.attr_accessor name
73
+ @schema[name] = :float
74
+ end
75
+
76
+ def datetime(name)
77
+ @model.attr_accessor name
78
+ @schema[name] = :datetime
79
+ end
80
+
81
+ end
82
+ end
@@ -0,0 +1,3 @@
1
+ module LocalModel
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,40 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "local_model/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "local_model"
8
+ spec.version = LocalModel::VERSION
9
+ spec.authors = ["Micah Shute"]
10
+ spec.email = ["micah.shute@gmail.com"]
11
+
12
+ spec.summary = %q{Easily set up a schema persisted with CSV but interactable with AR-like methods}
13
+ spec.description = %q{This is meant to help facilitate an API-first strategy when creating web apps with RoR}
14
+ spec.homepage = "https://github.com/micahshute/local_model"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ if spec.respond_to?(:metadata)
20
+ spec.metadata["homepage_uri"] = spec.homepage
21
+ spec.metadata["source_code_uri"] = "https://github.com/micahshute/local_model"
22
+ spec.metadata["changelog_uri"] = "https://github.com/micahshute/local_model"
23
+ else
24
+ raise "RubyGems 2.0 or newer is required to protect against " \
25
+ "public gem pushes."
26
+ end
27
+
28
+ # Specify which files should be added to the gem when it is released.
29
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
30
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
31
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
32
+ end
33
+ spec.bindir = "exe"
34
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
35
+ spec.require_paths = ["lib"]
36
+
37
+ spec.add_development_dependency "bundler", "~> 2.2"
38
+ spec.add_development_dependency "rake", "~> 13.0"
39
+ spec.add_development_dependency "rspec", "~> 3.10"
40
+ end
metadata ADDED
@@ -0,0 +1,113 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: local_model
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Micah Shute
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-05-10 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.2'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.2'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '13.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '13.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.10'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.10'
55
+ description: This is meant to help facilitate an API-first strategy when creating
56
+ web apps with RoR
57
+ email:
58
+ - micah.shute@gmail.com
59
+ executables: []
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - ".gitignore"
64
+ - ".rspec"
65
+ - ".travis.yml"
66
+ - CODE_OF_CONDUCT.md
67
+ - Gemfile
68
+ - Gemfile.lock
69
+ - LICENSE.txt
70
+ - README.md
71
+ - Rakefile
72
+ - bin/console
73
+ - bin/setup
74
+ - lib/local_model.rb
75
+ - lib/local_model/adapters/boolean_adapter.rb
76
+ - lib/local_model/adapters/datetime_adapter.rb
77
+ - lib/local_model/adapters/float_adapter.rb
78
+ - lib/local_model/adapters/integer_adapter.rb
79
+ - lib/local_model/adapters/string_adapter.rb
80
+ - lib/local_model/concerns/csv_interactable.rb
81
+ - lib/local_model/csv.rb
82
+ - lib/local_model/helpers/functions.rb
83
+ - lib/local_model/helpers/pluralized_words.rb
84
+ - lib/local_model/model.rb
85
+ - lib/local_model/version.rb
86
+ - local_model.gemspec
87
+ homepage: https://github.com/micahshute/local_model
88
+ licenses:
89
+ - MIT
90
+ metadata:
91
+ homepage_uri: https://github.com/micahshute/local_model
92
+ source_code_uri: https://github.com/micahshute/local_model
93
+ changelog_uri: https://github.com/micahshute/local_model
94
+ post_install_message:
95
+ rdoc_options: []
96
+ require_paths:
97
+ - lib
98
+ required_ruby_version: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - ">="
101
+ - !ruby/object:Gem::Version
102
+ version: '0'
103
+ required_rubygems_version: !ruby/object:Gem::Requirement
104
+ requirements:
105
+ - - ">="
106
+ - !ruby/object:Gem::Version
107
+ version: '0'
108
+ requirements: []
109
+ rubygems_version: 3.2.3
110
+ signing_key:
111
+ specification_version: 4
112
+ summary: Easily set up a schema persisted with CSV but interactable with AR-like methods
113
+ test_files: []