Sha256: f79219f8f1177d948bb1b108cdda777bd3a45656daf7f9c93a76fa19a6ddee37

Contents?: true

Size: 1.23 KB

Versions: 8

Compression:

Stored size: 1.23 KB

Contents

require "active_support/core_ext/module/delegation"

module StudyEngine
  class Form
    include ActiveModel::Validations
    extend ActiveModel::Naming

    def self.wraps(model)
      @wraps = model
    end

    def self.model_name
      ActiveModel::Name.new(wrapped_class)
    end

    def self.wrapped_class
      @wraps.to_s.classify.constantize
    end

    def self.lookup_ancestors
      [self]
    end

    cattr_accessor(:attributes_list) { [] }

    def self.attributes *attributes
      attributes.each do |attribute|
        attributes_list << attribute
        attr_accessor attribute
      end
    end

    def self.new_from_model model
      attributes = model.attributes.slice(*attributes_list.map(&:to_s))
      new attributes
    end

    def initialize attributes = {}, model = self.class.wrapped_class.new
      @model = model
      attributes.each do |name, value|
        send("#{name}=", value)
      end
    end

    def attributes
      attributes_list.reduce({}) do |hash, key|
        hash[key] = send(key)
        hash
      end
    end

    def save
      @model.update_attributes(attributes) if valid?
    end

    delegate :to_model, :to_key, :to_param, :to_partial_path, :persisted?, :new_record?, to: :@model
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
study_engine-0.3.1 app/models/study_engine/form.rb
study_engine-0.3.0 app/models/study_engine/form.rb
study_engine-0.2.2 app/models/study_engine/form.rb
study_engine-0.2.1 app/models/study_engine/form.rb
study_engine-0.2.0 app/models/study_engine/form.rb
study_engine-0.1.1 app/models/study_engine/form.rb
study_engine-0.1.0 app/models/study_engine/form.rb
study_engine-0.0.2 app/models/study_engine/form.rb