Skip to content

Instantly share code, notes, and snippets.

@datt
Last active December 29, 2015 13:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save datt/7674976 to your computer and use it in GitHub Desktop.
Save datt/7674976 to your computer and use it in GitHub Desktop.
The common creator methods can be written in base creator which can be again overridden by other creators. An example of using creator is also given. To know more about Creator follow (https://github.com/datt/Creators)
class BaseCreator < Creators::Base
EXTRA_PARAMS = [:action, :controller, :format,:utf8,:authenticity_token]
def initialize(raw_params, model)
super(raw_params,model)
end
def refine_params
@params.deep_symbolize_keys.delete_if{|k,v| EXTRA_PARAMS.include? k }
end
private
#define: This will remove extra spaces from params.
#TODO: Remove password and other sensible fields.
def strip_params params
case params
when Array
params.map { |v| strip_params(v) }
when Hash
Hash[params.map { |k, v| [k, strip_params(v)] }]
when String
params.strip!
end
end
#define: This method will convert truth values(1,0,"t","f") into boolean values.
def convert_params params
bool_params = convert_to_bool params
params.replace(bool_params) if params.is_a?(Hash)
params
end
def convert_to_bool params
case params
when Array
params.map { |v| convert_to_bool(v) }
when Hash
Hash[params.map { |k, v| [k, convert_to_bool(v)] }]
when String
to_bool(params)
end
end
def to_bool val
return true if ['true', 'yes', 'on', 't'].include? val
return false if ['false', 'no', 'off', 'f'].include? val
return val
end
end
class ProfileCreator < BaseCreator
def initialize(raw_params,profile)
super(raw_params, profile)
end
def refine_params # optional
super
strip_params(@params)
convert_params(@params['profile']['settings'])
end
end
class ProfilesController < ApplicationController
before_filter :new_user_profile, :only=>[:new, :create]
def new
end
def create
#params {"utf8"=>"✓", "authenticity_token"=>"PV3s45++WCzqw6pTAikXC6NINcERtcxzBdY+CI3lXfc=", "profile"=>{"first_name"=>"fname ", "last_name"=>"last name ", "address1"=>" Address1 ", "address2"=>"Address 2", "city"=>"Pune", "state"=>"7", "zip"=>"411067", "phone_number"=>"1234567890","settings"=> {"private"=>"true","visible"=>"0"}}, "commit"=>"Next"}
ProfileCreator.new(params,@profile).save
end
private
def new_user_profile
@profile = current_user.build_profile
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment