Skip to content

Instantly share code, notes, and snippets.

@rossmari
Created October 9, 2014 07:11
Show Gist options
  • Save rossmari/afccf4fefff1e9212e17 to your computer and use it in GitHub Desktop.
Save rossmari/afccf4fefff1e9212e17 to your computer and use it in GitHub Desktop.
50% of multi class form presenter - #useless
class Magazine::FormPresenter < ActiveRecord::Base
# === CONSTANTS
CONSTANT_EXCEPT = [:id, :created_at, :updated_at, :type]
# === COLUMN METHODS
class << self
def columns
@columns ||= [];
end
def column(name, sql_type = nil, default = nil, null = true)
columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
end
end
def self.get_class_instance
wide_instance = Class.new(Magazine::FormPresenter) do
def self.name
'Magazine::FormPresenter'
end
end
return wide_instance
end
def self.create_columns(template_class, except = [])
except = except + CONSTANT_EXCEPT
template_class.columns.each do |col|
next if except.include?(col.name.to_sym)
self.column(col.name, col.type, col.default, col.null)
end
template_class.reflect_on_all_associations.each do |as|
class_name = as.options[:class_name].presence || as.name.to_s.classify
self.class_eval("#{as.macro}(:#{as.name}, class_name: '#{class_name}')")
end
end
end
class Magazine::PublicationFormPresenter
def self.create_presenter
presenter_class = Magazine::FormPresenter.get_class_instance
presenter_class.create_columns(Magazine::Set, [:publication_id, :price, :state, :user_id, :mood_id])
presenter_class.create_columns(Magazine::AutoPublication, [:price, :words_count, :release_id, :ptype, :user_id, :state, :template_id])
presenter_class.create_columns(Magazine::AutoTemplate)
return presenter_class.new
end
end
class Magazine::FormExtractor
def initialize(params)
@params = params
end
def assign_attributes(extracted_class)
instance = extracted_class.new
instance.attributes.each do |key, value|
if @params.keys.include?(key.to_s)
instance.send("#{key}=", @params[key.to_s])
end
end
return instance
end
def extract_set
set = assign_attributes(Magazine::Set)
set.releases = Magazine::Release.find(@params['release_ids'].select{|v| !v.blank?})
return set
end
def extract_template
template = assign_attributes(Magazine::AutoTemplate)
return template
end
def extract_publication
publication = assign_attributes(Magazine::AutoPublication)
return publication
end
def extract(user)
template = extract_template
publication = extract_publication
publication.template = template
set = extract_set
set.publication = publication
set.user = user
return set, publication, template
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment