-
-
Save absyah/4bf6db8a245a894ef1d4673de9235ae1 to your computer and use it in GitHub Desktop.
Rails utility class for objets to act like ActiveRecord::Base
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
# Base class to inherit from for objects to act like ActiveRecord::Base | |
# without using a database. Lets you use validations, errors, forms, routes. | |
# | |
# Example: | |
# class Exporter < Base | |
# attributes_accessor :email, :data | |
# end | |
class Base | |
extend ActiveModel::Naming | |
include ActiveModel::Serialization | |
include ActiveModel::Validations | |
# Stores all attributes in a hash | |
attr_accessor :attributes | |
def initialize(attributes = {}) | |
@attributes = attributes | |
end | |
def to_model() self end | |
def to_key() false end | |
def new_record?() true end | |
def persisted?() false end | |
# Create readers and writers that store the data in @attributes | |
# Example: | |
# attributes_reader :bar | |
# attributes_writer :foo | |
# attributes_accessor :spam, :wham | |
def self.attributes_accessor(*syms) | |
attributes_reader(*syms) | |
attributes_writer(*syms) | |
end | |
def self.attributes_reader(*syms) | |
syms.each do |sym| | |
class_eval(<<-EOS, __FILE__, __LINE__ + 1) | |
def #{sym} | |
@attributes[:#{sym}] | |
end | |
def #{sym}? | |
not @attributes[:#{sym}].blank? and @attributes[:#{sym}] != "0" | |
end | |
EOS | |
end | |
end | |
def self.attributes_writer(*syms) | |
syms.each do |sym| | |
class_eval(<<-EOS, __FILE__, __LINE__ + 1) | |
def #{sym}=(obj) | |
@attributes[:#{sym}] = obj | |
end | |
EOS | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment