Skip to content

Instantly share code, notes, and snippets.

@dux
Last active October 28, 2018 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dux/e2d407f983cb3ad6f51da88e29cb9581 to your computer and use it in GitHub Desktop.
Save dux/e2d407f983cb3ad6f51da88e29cb9581 to your computer and use it in GitHub Desktop.
Foder and Generic models
# frozen_string_literal: true
class FolderModel
class << self
def find(key)
new(key)
end
def all
Dir["db/#{self.to_s.tableize}/*.json"].map{|file| new file.split('/').last.sub('.json') }
end
end
###
def [](key)
@data[key]
end
def []=(key, value)
@data[key] = value
end
def method_missing(name, *args)
func = name.to_s.split('=')[0].to_sym
if name.to_s.index('=')
@data[func] = args[0]
else
# raise "Field #{name} not found"
@data[func]
end
end
def save
@storage.write JSON.pretty_generate(@data)
@data
end
alias :save! :save
def initialize(key)
@key = key
@storage = Pathname.new("db/#{self.class.to_s.tableize}/#{key}.json")
@data = JSON.parse @storage.read
@data = @data.h
end
end
# frozen_string_literal: true
# class FooBar < GenericModel
#
# values [1, 'LinkedIn'],
# [2, 'Facebook'],
# [3, 'Twitter'],
# [4, 'Google'],
# [5, 'Email'],
# [6, 'Mobile']
#
# def ico
# %{<img src="/images/type/#{code}.png" style="width:16px; height:16px; vertical-align:middle; " />}
# end
#
# end
class GenericModel
@@values = {}
class << self
def values vals
@@values[self.to_s] = []
vals.map { |el| add_value(el) }
end
def add_value val
o = new(val)
for key in val.keys
eval %[def o.#{key}; @_vals[:#{key}]; end]
end
@@values[self.to_s].push(o)
end
def find id
for el in all
return el if el.id == id
end
nil
end
def all
@@values[self.to_s]
end
def where opts
@@values[self.to_s].select{ |el| el[opts.keys[0]] == opts.values[0] }
end
end
###
def initialize vals
@_vals = vals
end
def [] key
@_vals[key]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment