Share Variables between Methods in a Rails Controller - ruby-on-rails

I have a Rails controller that has 2 methods. Both Methods use some of the same variables and I'm wondering how I can refactor this into either a method in the Model of somewhere in the controller to make them more reusable than they are now.
class ChartsController < ApplicationController
before_filter :authenticate_user!, :company_id
def service_level
latest_date = Invoice.where(:account_id => #company.accounts).maximum(:invc_date)
invoices_filter = { :invoices => { :invc_date => (latest_date - 3.months)..latest_date } }
invoices = Invoice.where({:account_id => #company.accounts}.merge(invoices_filter))
details = InvoiceDetail.joins(:type).where(:invoice_id => invoices)
freight_details = details.where(:invoice_detail_types => { :category => 'freight' })
freight_groups = freight_details.group(:family).select("family, count(distinct package_id), sum(base_charge + discount)")
vol_data = {}
spend_data = {}
#charts = {}
#charts[:service_analysis] = {
:vol_data => Hash[freight_groups.map { |row| [InvoiceDetailFamily[row.family].name, row.count.to_i] }],
:spend_data => Hash[freight_groups.map { |row| [InvoiceDetailFamily[row.family].name, row.sum.to_f] }]
}
render partial: 'service_level'
end
def weight_summary
latest_date = Invoice.where(:account_id => #company.accounts).maximum(:invc_date)
invoices_filter = { :invoices => { :invc_date => (latest_date - 3.months)..latest_date } }
invoices = Invoice.where({:account_id => #company.accounts}.merge(invoices_filter))
details = InvoiceDetail.joins(:type).where(:invoice_id => invoices)
freight_details = details.where(:invoice_detail_types => { :category => 'freight' })
packages = freight_details.joins(:package, :invoice)
vol_data = {}
spend_data = {}
packages.group(:zone).select("zone, count(distinct package_id), sum(base_charge + discount)").each do |row|
case row.zone
when '02'..'08', '002'..'008', '102'..'108', '132'..'138', '202'..'208', '242'..'248', '302'..'308'
zg = row.zone[-1]
when '09'..'17', '124'..'126', '224'..'226'
zg = 'AK/HI/PR'
else
zg = 'Import/Export'
end
vol_data[zg] = (vol_data[zg] || 0) + row.count.to_i
spend_data[zg] = (spend_data[zg] || 0) + row.sum.to_f
end
#charts = {}
#charts[:weight_analysis] = {
:vol_data => Hash[(vol_data.sort_by {|key, value| key.scan(/\d+/)[0].to_i})],
:spend_data => Hash[(spend_data.sort_by {|key, value| key.scan(/\d+/)[0].to_i})]
}
render partial: 'weight_summary'
end
end

I would suggest to use a model class method for processing data. for example
freight_details = details.where(:invoice_detail_types => { :category => 'freight' })
freight_groups = freight_details.group(:family).select("family, count(distinct package_id), sum(base_charge + discount)")
vol_data = {}
spend_data = {}
#charts = {}
#charts[:service_analysis] = {
:vol_data => Hash[freight_groups.map { |row| [InvoiceDetailFamily[row.family].name, row.count.to_i] }],
:spend_data => Hash[freight_groups.map { |row| [InvoiceDetailFamily[row.family].name, row.sum.to_f] }]
}
could be moved to a model class method that returns charts. In the same way you can refactor your second method. Any kind of business logic and data proccessing should be handled in models
Moreover I can see there are too many unused local variables are there in controller. The controller should be thin as much as possible.

Use concept like decorator
module Chart
extend self
def service_analysis(freight_groups, freight_groups)
end
end
class ChartsController < ApplicationController
#chart = Chart.service_analysis(freight_groups, freight_groups)
end
notes: do not put calculation code in view, it's slow

If you decided to keep it within the controller, then try this:
class ChartsController < ApplicationController
before_filter :authenticate_user!, :company_id
before_filter :load_data, :only => [:service_level, weight_summary]
def service_level
freight_groups = #freight_details.group(:family).select("family, count(distinct package_id), sum(base_charge + discount)")
#charts = {}
#charts[:service_analysis] = {
:vol_data => Hash[freight_groups.map { |row| [InvoiceDetailFamily[row.family].name, row.count.to_i] }],
:spend_data => Hash[freight_groups.map { |row| [InvoiceDetailFamily[row.family].name, row.sum.to_f] }]
}
render partial: 'service_level'
end
def weight_summary
packages = #freight_details.joins(:package, :invoice)
vol_data = {}
spend_data = {}
packages.group(:zone).select("zone, count(distinct package_id), sum(base_charge + discount)").each do |row|
case row.zone
when '02'..'08', '002'..'008', '102'..'108', '132'..'138', '202'..'208', '242'..'248', '302'..'308'
zg = row.zone[-1]
when '09'..'17', '124'..'126', '224'..'226'
zg = 'AK/HI/PR'
else
zg = 'Import/Export'
end
vol_data[zg] = (vol_data[zg] || 0) + row.count.to_i
spend_data[zg] = (spend_data[zg] || 0) + row.sum.to_f
end
#charts = {}
#charts[:weight_analysis] = {
:vol_data => Hash[(vol_data.sort_by {|key, value| key.scan(/\d+/)[0].to_i})],
:spend_data => Hash[(spend_data.sort_by {|key, value| key.scan(/\d+/)[0].to_i})]
}
render partial: 'weight_summary'
end
private
def load_data
latest_date = Invoice.where(:account_id => #company.accounts).maximum(:invc_date)
invoices_filter = { :invoices => { :invc_date => (latest_date - 3.months)..latest_date } }
invoices = Invoice.where({:account_id => #company.accounts}.merge(invoices_filter))
details = InvoiceDetail.joins(:type).where(:invoice_id => invoices)
#freight_details = details.where(:invoice_detail_types => { :category => 'freight' })
end
end
The instance variable #freight_details will be available in both methods. The before_filter will execute the load_data method only for these two methods.
Good Luck!

Related

Ruby - PG::UndefinedTable: ERROR: missing FROM-clause entry for table

I'm getting the following error when I'm trying to query another table in a model definition.
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "miq_user_roles" LINE 1: ..." = $1 AND "service_templates"."display" = $2 AND "miq_user_... ^ [catalog/explorer]
Any idea how to resolve this?
scope :with_service_template_catalog_id, ->(cat_id) { where(:service_template_catalog_id => cat_id) }
scope :without_service_template_catalog_id, -> { where(:service_template_catalog_id => nil) }
scope :with_existent_service_template_catalog_id, -> { where.not(:service_template_catalog_id => nil) }
scope :displayed, -> { where(:display => true) }
scope :public_service_templates, -> { where("miq_user_roles.settings" => nil) }
Here is the full code:
class ServiceTemplate < ApplicationRecord
include SupportsFeatureMixin
DEFAULT_PROCESS_DELAY_BETWEEN_GROUPS = 120
GENERIC_ITEM_SUBTYPES = {
"custom" => N_("Custom"),
"vm" => N_("Virtual Machine"),
"playbook" => N_("Playbook"),
"hosted_database" => N_("Hosted Database"),
"load_balancer" => N_("Load Balancer"),
"storage" => N_("Storage")
}.freeze
SERVICE_TYPE_ATOMIC = 'atomic'.freeze
SERVICE_TYPE_COMPOSITE = 'composite'.freeze
RESOURCE_ACTION_UPDATE_ATTRS = [:dialog,
:dialog_id,
:fqname,
:configuration_template,
:configuration_template_id,
:configuration_template_type].freeze
include CustomActionsMixin
include ServiceMixin
include OwnershipMixin
include NewWithTypeStiMixin
include TenancyMixin
include ArchivedMixin
include CiFeatureMixin
include_concern 'Filter'
include_concern 'Copy'
validates :name, :presence => true
belongs_to :tenant
has_many :service_templates, :through => :service_resources, :source => :resource, :source_type => 'ServiceTemplate'
has_many :services
has_many :service_template_tenants, :dependent => :destroy
has_many :additional_tenants, :through => :service_template_tenants, :source => :tenant, :dependent => :destroy
has_one :picture, :dependent => :destroy, :as => :resource, :autosave => true
belongs_to :service_template_catalog
belongs_to :zone
belongs_to :currency, :inverse_of => false
has_many :dialogs, -> { distinct }, :through => :resource_actions
has_many :miq_schedules, :as => :resource, :dependent => :destroy
has_many :miq_requests, :as => :source, :dependent => :nullify
has_many :active_requests, -> { where(:request_state => MiqRequest::ACTIVE_STATES) }, :as => :source, :class_name => "MiqRequest"
virtual_column :type_display, :type => :string
virtual_column :template_valid, :type => :boolean
virtual_column :template_valid_error_message, :type => :string
virtual_column :archived, :type => :boolean
virtual_column :active, :type => :boolean
default_value_for :internal, false
default_value_for :service_type, SERVICE_TYPE_ATOMIC
default_value_for(:generic_subtype) { |st| 'custom' if st.prov_type == 'generic' }
virtual_has_one :config_info, :class_name => "Hash"
scope :with_service_template_catalog_id, ->(cat_id) { where(:service_template_catalog_id => cat_id) }
scope :without_service_template_catalog_id, -> { where(:service_template_catalog_id => nil) }
scope :with_existent_service_template_catalog_id, -> { where.not(:service_template_catalog_id => nil) }
scope :displayed, -> { where(:display => true) }
scope :public_service_templates, -> { where("miq_user_roles.settings" => nil) }
supports :order do
unsupported_reason_add(:order, 'Service template does not belong to a service catalog') unless service_template_catalog
unsupported_reason_add(:order, 'Service template is not configured to be displayed') unless display
end
alias orderable? supports_order?
alias validate_order supports_order?
def self.with_tenant(tenant_id)
tenant = Tenant.find(tenant_id)
where(:tenant_id => tenant.ancestor_ids + [tenant_id])
end
def self.with_additional_tenants
references(table_name, :tenants).includes(:service_template_tenants => :tenant)
end
def self.all_catalog_item_types
#all_catalog_item_types ||= begin
builtin_catalog_item_types = {
"generic" => N_("Generic"),
"generic_orchestration" => N_("Orchestration"),
}
ExtManagementSystem.subclasses_supporting(:catalog)
.flat_map(&:catalog_types)
.reduce(builtin_catalog_item_types, :merge)
end
end
def self.catalog_item_types
ems_classes = Rbac.filtered(ExtManagementSystem.all).collect(&:class).uniq.select { |ems| ems.supports?(:catalog) }
ci_types = Set.new(ems_classes.flat_map(&:catalog_types).reduce({}, :merge).keys)
ci_types.add('generic_orchestration') if Rbac.filtered(OrchestrationTemplate).exists?
ci_types.add('generic')
all_catalog_item_types.each.with_object({}) do |(key, description), hash|
hash[key] = {:description => description, :display => ci_types.include?(key)}
end
end
def self.create_catalog_item(options, auth_user)
transaction do
create_from_options(options).tap do |service_template|
config_info = options[:config_info].except(:provision, :retirement, :reconfigure)
workflow_class = MiqProvisionWorkflow.class_for_source(config_info[:src_vm_id])
if workflow_class
request = workflow_class.new(config_info, auth_user).make_request(nil, config_info)
service_template.add_resource(request)
end
service_template.create_resource_actions(options[:config_info])
end
end
end
def self.class_from_request_data(data)
request_type = data['prov_type']
if request_type.include?('generic_')
generic_type = request_type.split('generic_').last
"ServiceTemplate#{generic_type.camelize}".constantize
else
ServiceTemplate
end
end
def update_catalog_item(options, auth_user = nil)
config_info = validate_update_config_info(options)
unless config_info
update!(options)
return reload
end
transaction do
update_from_options(options)
update_service_resources(config_info, auth_user)
update_resource_actions(config_info)
save!
end
reload
end
def children
service_templates
end
def descendants
children.flat_map { |child| [child] + child.descendants }
end
def subtree
[self] + descendants
end
def vms_and_templates
[]
end
def destroy
if parent_services.present?
raise MiqException::MiqServiceError, _("Cannot delete a service that is the child of another service.")
end
service_resources.each do |sr|
rsc = sr.resource
rsc.destroy if rsc.kind_of?(MiqProvisionRequestTemplate)
end
super
end
def archive
raise _("Cannot archive while in use") unless active_requests.empty?
archive!
end
def retireable?
false
end
def request_class
ServiceTemplateProvisionRequest
end
def request_type
"clone_to_service"
end
def config_info
options[:config_info] || construct_config_info
end
def create_service(service_task, parent_svc = nil)
nh = attributes.dup
# Service#display was renamed to #visible in https://github.com/ManageIQ/manageiq-schema/pull/410
nh['visible'] = nh.delete('display') if nh.key?('display')
nh['options'][:dialog] = service_task.options[:dialog]
(nh.keys - Service.column_names + %w(created_at guid service_template_id updated_at id type prov_type)).each { |key| nh.delete(key) }
# Hide child services by default
nh['visible'] = false if parent_svc
# If visible is nil, set it to false
nh['visible'] ||= false
# convert template class name to service class name by naming convention
nh['type'] = self.class.name.sub('Template', '')
nh['initiator'] = service_task.options[:initiator] if service_task.options[:initiator]
service = Service.create!(nh) do |svc|
svc.service_template = self
set_ownership(svc, service_task.get_user)
service_resources.each do |sr|
nh = sr.attributes.dup
%w(id created_at updated_at service_template_id).each { |key| nh.delete(key) }
svc.add_resource(sr.resource, nh) unless sr.resource.nil?
end
end
service.tap do |svc|
if parent_svc
service_resource = ServiceResource.find_by(:id => service_task.options[:service_resource_id])
parent_svc.add_resource!(svc, service_resource)
end
end
end
def composite?
service_type.to_s.include?(self.class::SERVICE_TYPE_COMPOSITE)
end
def atomic?
service_type.to_s.include?(self.class::SERVICE_TYPE_ATOMIC)
end
def type_display
case service_type
when self.class::SERVICE_TYPE_ATOMIC then "Item"
when self.class::SERVICE_TYPE_COMPOSITE then "Bundle"
when nil then "Unknown"
else
service_type.to_s.capitalize
end
end
def create_tasks_for_service(service_task, parent_svc)
unless parent_svc
return [] unless self.class.include_service_template?(service_task,
service_task.source_id,
parent_svc)
end
svc = create_service(service_task, parent_svc)
service_task.destination = svc
create_subtasks(service_task, svc)
end
# default implementation to create subtasks from service resources
def create_subtasks(parent_service_task, parent_service)
tasks = []
service_resources.each do |child_svc_rsc|
scaling_min = child_svc_rsc.scaling_min
1.upto(scaling_min).each do |scaling_idx|
nh = parent_service_task.attributes.dup
%w(id created_on updated_on type state status message).each { |key| nh.delete(key) }
nh['options'] = parent_service_task.options.dup
nh['options'].delete(:child_tasks)
# Initial Options[:dialog] to an empty hash so we do not pass down dialog values to child services tasks
nh['options'][:dialog] = {}
next if child_svc_rsc.resource_type == "ServiceTemplate" &&
!self.class.include_service_template?(parent_service_task,
child_svc_rsc.resource.id,
parent_service)
new_task = parent_service_task.class.new(nh)
new_task.options.merge!(
:src_id => child_svc_rsc.resource.id,
:scaling_idx => scaling_idx,
:scaling_min => scaling_min,
:service_resource_id => child_svc_rsc.id,
:parent_service_id => parent_service.id,
:parent_task_id => parent_service_task.id,
)
new_task.state = 'pending'
new_task.status = 'Ok'
new_task.source = child_svc_rsc.resource
new_task.save!
new_task.after_request_task_create
parent_service_task.miq_request.miq_request_tasks << new_task
tasks << new_task
end
end
tasks
end
def set_ownership(service, user)
return if user.nil?
service.evm_owner = user
if user.current_group
$log.info("Setting Service Owning User to Name=#{user.name}, ID=#{user.id}, Group to Name=#{user.current_group.name}, ID=#{user.current_group.id}")
service.miq_group = user.current_group
else
$log.info("Setting Service Owning User to Name=#{user.name}, ID=#{user.id}")
end
end
def self.default_provisioning_entry_point(service_type)
if service_type == 'atomic'
'/Service/Provisioning/StateMachines/ServiceProvision_Template/CatalogItemInitialization'
else
'/Service/Provisioning/StateMachines/ServiceProvision_Template/CatalogBundleInitialization'
end
end
def self.default_retirement_entry_point
'/Service/Retirement/StateMachines/ServiceRetirement/Default'
end
def self.default_reconfiguration_entry_point
nil
end
def template_valid?
validate_template[:valid]
end
alias template_valid template_valid?
def template_valid_error_message
validate_template[:message]
end
def validate_template
missing_resources = service_resources.select { |sr| sr.resource.nil? }
if missing_resources.present?
missing_list = missing_resources.collect { |sr| "#{sr.resource_type}:#{sr.resource_id}" }.join(", ")
return {:valid => false,
:message => "Missing Service Resource(s): #{missing_list}"}
end
service_resources.detect do |s|
r = s.resource
r.respond_to?(:template_valid?) && !r.template_valid?
end.try(:resource).try(:validate_template) || {:valid => true, :message => nil}
end
def provision_action
resource_actions.find_by(:action => "Provision")
end
def update_resource_actions(ae_endpoints)
resource_action_list.each do |action|
resource_params = ae_endpoints[action[:param_key]]
resource_action = resource_actions.find_by(:action => action[:name])
# If the action exists in updated parameters
if resource_params
# And the resource action exists on the template already, update it
if resource_action
resource_action.update!(resource_params.slice(*RESOURCE_ACTION_UPDATE_ATTRS))
# If the resource action does not exist, create it
else
build_resource_action(resource_params, action)
end
elsif resource_action
# If the endpoint does not exist in updated parameters, but exists on the template, delete it
resource_action.destroy
end
end
end
def create_resource_actions(ae_endpoints)
ae_endpoints ||= {}
resource_action_list.each do |action|
ae_endpoint = ae_endpoints[action[:param_key]]
next unless ae_endpoint
build_resource_action(ae_endpoint, action)
end
save!
end
def self.create_from_options(options)
create!(options.except(:config_info).merge(:options => { :config_info => options[:config_info] }))
end
private_class_method :create_from_options
def provision_request(user, options = nil, request_options = {})
request_options[:provision_workflow] = true
request_options[:parent_id] = options.delete('param_parent_request_id') unless options['param_parent_request_id'].nil?
result = order(user, options, request_options)
raise result[:errors].join(", ") if result[:errors].any?
result[:request]
end
def picture=(value)
if value.kind_of?(Hash)
super(Picture.new(value))
else
super
end
end
def queue_order(user_id, options, request_options)
MiqQueue.submit_job(
:class_name => self.class.name,
:instance_id => id,
:method_name => "order",
:args => [user_id, options, request_options],
)
end
def order(user_or_id, options = nil, request_options = {}, schedule_time = nil)
user = user_or_id.kind_of?(User) ? user_or_id : User.find(user_or_id)
workflow = provision_workflow(user, options, request_options)
if schedule_time
require 'time'
time = Time.parse(schedule_time).utc
errors = workflow.validate_dialog
errors << unsupported_reason(:order)
return {:errors => errors} if errors.compact.present?
schedule = MiqSchedule.create!(
:name => "Order #{self.class.name} #{id} at #{time}",
:description => "Order #{self.class.name} #{id} at #{time}",
:sched_action => {:args => [user.id, options, request_options], :method => "queue_order"},
:resource => self,
:run_at => {
:interval => {:unit => "once"},
:start_time => time,
:tz => "UTC",
},
)
{:schedule => schedule}
else
workflow.submit_request
end
end
def provision_workflow(user, dialog_options = nil, request_options = {})
dialog_options ||= {}
request_options.delete(:provision_workflow) if request_options[:submit_workflow]
ra_options = request_options.slice(:initiator, :init_defaults, :provision_workflow, :submit_workflow).merge(:target => self)
ResourceActionWorkflow.new(dialog_options, user, provision_action, ra_options).tap do |wf|
wf.request_options = request_options
end
end
def add_resource(rsc, options = {})
super
adjust_service_type
end
def self.display_name(number = 1)
n_('Service Catalog Item', 'Service Catalog Items', number)
end
def my_zone
# Catalog items can specify a zone to run in.
# Catalog bundle are used for grouping catalog items and are therefore treated as zone-agnostic.
zone&.name if atomic?
end
private
def update_service_resources(config_info, auth_user = nil)
config_info = config_info.except(:provision, :retirement, :reconfigure)
workflow_class = MiqProvisionWorkflow.class_for_source(config_info[:src_vm_id])
if workflow_class
service_resources.find_by(:resource_type => 'MiqRequest').try(:destroy)
new_request = workflow_class.new(config_info, auth_user).make_request(nil, config_info)
add_resource!(new_request)
end
end
def build_resource_action(ae_endpoint, action)
fqname = ae_endpoint[:fqname] || self.class.send(action[:method], *action[:args]) || ""
build_options = {:action => action[:name],
:fqname => fqname,
:ae_attributes => {:service_action => action[:name]}}
build_options.merge!(ae_endpoint.slice(*RESOURCE_ACTION_UPDATE_ATTRS))
resource_actions.build(build_options)
end
def validate_update_config_info(options)
if options[:service_type] && options[:service_type] != service_type
raise _('service_type cannot be changed')
end
if options[:prov_type] && options[:prov_type] != prov_type
raise _('prov_type cannot be changed')
end
options[:config_info]
end
def resource_action_list
[
{:name => ResourceAction::PROVISION,
:param_key => :provision,
:method => 'default_provisioning_entry_point',
:args => [service_type]},
{:name => ResourceAction::RECONFIGURE,
:param_key => :reconfigure,
:method => 'default_reconfiguration_entry_point',
:args => []},
{:name => ResourceAction::RETIREMENT,
:param_key => :retirement,
:method => 'default_retirement_entry_point',
:args => []}
]
end
def update_from_options(params)
options[:config_info] = params[:config_info]
update!(params.except(:config_info))
end
def construct_config_info
config_info = {}
miq_request_resource = service_resources.find_by(:resource_type => 'MiqRequest')
config_info.merge!(miq_request_resource.resource.options.compact) if miq_request_resource
config_info.merge!(resource_actions_info)
end
def resource_actions_info
resource_actions.each_with_object({}) do |resource_action, config_info|
resource_options = resource_action.slice(:dialog_id, :configuration_template_type, :configuration_template_id).compact
resource_options[:fqname] = resource_action.fqname
config_info[resource_action.action.downcase.to_sym] = resource_options.symbolize_keys
end
end
def generic_custom_buttons
CustomButton.buttons_for("Service")
end
def adjust_service_type
self.service_type = service_resources.any? { |st| st.resource_type.in?(['Service', 'ServiceTemplate']) } ? self.class::SERVICE_TYPE_COMPOSITE : self.class::SERVICE_TYPE_ATOMIC
end
end
scope :public_service_templates, -> {
joins(:miq_user_roles).where(miq_user_roles: { settings: nil })
}
Assuming the table exists. You need to join on that table in order to query it. Note, the default joins is an inner join that will remove records that don't have an associated miq_user_roles.
This will change the query substantially. If a record has_many miq_user_roles you'll likely need to add a distinct or distinct on clause. If it's possible to have no miq_user_roles, then records without them will now dissappear when you call the scope, since the inner join didn't find any.

how to pass extra parameter to as_json from controller to model

There are two apis in a controller. I need image for main_category and icon for nav-category. How can i pass xtra parameter from controller and can differentiate in model that this request is from main_category and this is from nav_category. Please help.
def main_category
category = Category.all
render :json => :include => {:success=> true,:data => category.as_json(#a,:only => [:name,:image_url])}
end
def nav_category
category = Category.all
render :json => {:success=> true,:data => category.as_json(:only => [:name,:icon_url])}
end
as_json in model is as :
def as_json(options = { })
if self.id == nil
category = self.category
elsif(#a=='main')
h = super(options)
h[:image_url]= "http://#{$request.try(:host_with_port)}#{self.image.url}"
h
else
h = super(options)
h[:image_url]= "http://#{$request.try(:host_with_port)}#{self.image.url}"
h[:icon_url]= "http://#{$request.try(:host_with_port)}#{self.icon.url}"
h
end
end
I think what you need is passing custom option to as_json method to differentiate them.
Controller:
def main_category
categories = Category.all
render :json => {
:success=> true,
:data => categories.as_json(:only => [:name,:image_url], :category => "main")
}
end
def nav_category
categories = Category.all
render :json => {
:success=> true,
:data => categories.as_json(:only => [:name,:image_url], :category => "nav")
}
end
Model :
def as_json(options = { })
h = super(options)
if (options[:category] == 'main') {
h[:image_url]= "http://#{$request.try(:host_with_port)}#{self.image.url}"
} elsif (options[:category] == 'nav') {
h[:image_url]= "http://#{$request.try(:host_with_port)}#{self.image.url}"
h[:icon_url]= "http://#{$request.try(:host_with_port)}#{self.icon.url}"
}
h
end

PayPal Express Checkout with multiple items with active merchant in rails

I am trying to use PayPal ExpressCheckout button with multiple items but with no success.I am using NetBeans IDE, rails 4 and MySQL db.Here is what I did so far:
In my production.rb file I have:
Rails.application.configure do
config/application.rb.
config.after_initialize do
ActiveMerchant::Billing::Base.mode = :test
paypal_options = {
:login => "xxxx",
:password => "xxxx ",
:signature => "xxxx "
}
::STANDARD_GATEWAY = ActiveMerchant::Billing::PaypalGateway.new(paypal_options)
::EXPRESS_GATEWAY = ActiveMerchant::Billing::PaypalExpressGateway.new(paypal_options)
end
In my transaction.rb model I have:
def valid_purchase
if express_token.blank?
standard_purchase
else
express_token
end
def express_purchase
# price_in_cents = total
response = EXPRESS_GATEWAY.purchase(total, express_purchase_options)
if response.success?
self.status = "processed"
else
errors.add(:transactions, "---- #{response.message}.")
end
end
def express_token=(token)
self[:express_token] = token
if new_record? && !token.blank?
details = EXPRESS_GATEWAY.details_for(token)
self.express_payer_id = details.payer_id
self.ship_to_first_name = details.params["first_name"]
self.ship_to_last_name = details.params["last_name"]
end
end
private
def express_purchase_options
{
:ip => customer_ip,
:token => express_token,
:payer_id => express_payer_id
}
end
And in my transaction_controller.rb I have:
def express_checkout
order_items =[]
postage_rate=nil
item = Hash.new
#order = Order.find(session[:order_id])
#receipts = Receipt.where(:order_id=>#order.id)
#receipts.each do |r|
postage_rate = r.postage_rate * 100
end
#cart = Cart.find(#order.cart_id)
#cart.cart_items.each do |i|
#product = Product.find(i.product_id)
item = {
name: #product.product_name,
quantity: i.amount,
description: "ORDER_ID: #{#order.id}",
amount: #product.selling_price * 100 ,
shipping: postage_rate/#cart.cart_items.size
}
order_items << item
end
price_in_cents = (#order.total_p_pr * 100).round(2)
options = {
:ip => request.remote_ip,
:return_url => url_for(:action=>:new, :only_path => false),
:cancel_return_url => catalogs_traders_url,
:currency => "USD",
:allow_guest_checkout=> true,
:items => order_items # this line outputs: [{:name=>"owl potty", :quantity=>1, :description=>"ORDER_ID: 249", :amount=>2808.0, :shipping=>332.0}, {:name=>"a bag", :quantity=>1, :description=>"ORDER_ID: 249", :amount=>1260.0, :shipping=>332.0}, {:name=>"bracelet", :quantity=>1, :description=>"ORDER_ID: 249", :amount=>120.0, :shipping=>332.0}, {:name=>"beautiful woman", :quantity=>1, :description=>"ORDER_ID: 249", :amount=>74352.0, :shipping=>332.0}]
}
#passing the cost of the order
response = EXPRESS_GATEWAY.setup_purchase(price_in_cents,options )
redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token)
end
def new
#transaction = Transaction.new(:express_token => params[:token])
end
I get:
Any help will be more than welcome. Thank you!
I red this post very,very carefully
setting tax amount in Active Merchant / PayPal Express Checkout
and I understood my mistakes. Here is my corrected transaction_controller:
# to redirect to PayPay site
def express_checkout
pr = nil
tp = nil
items =[]
postage_r=[]
total_p = []
order_items =[]
postage_rate=nil
item = Hash.new
#order = Order.find(session[:order_id])
#receipts = Receipt.where(:order_id=>#order.id)
#receipts.each do |r|
total_p << r.total_price
postage_r << r.postage_rate
end
tp = total_p.inject{|sum,x| sum + x }
pr = postage_r.inject{|sum,x| sum + x }
#cart = Cart.find(#order.cart_id)
#cart.cart_items.each do |i|
#product = Product.find(i.product_id)
item = {
name: #product.product_name,
quantity: i.amount,
description: "ORDER_ID: #{#order.id}",
amount: #product.selling_price * 100 ,
}
order_items << item
end
price_in_cents = (#order.total_p_pr * 100).round(2)
options = {
:subtotal => tp * 100,
:shipping => pr * 100,
:handling => 0,
:tax => 0,
:ip => request.remote_ip,
:return_url => url_for(:action=>:new, :only_path => false),
:cancel_return_url => catalogs_traders_url,
:currency => "USD",
:allow_guest_checkout=> true,
:items => order_items
}
#passing the cost of the order
response = EXPRESS_GATEWAY.setup_purchase(price_in_cents,options )
redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token)
end
It worked. I hope my post will be useful for someone who want to integrate Express Checkout button. Thank you for all your help!

Mongoid query - Refine Search Implementation

I am working on refine search in Rails4 and Mongoid. This is my search params and form,
I built the query piece by piece:
if params[:procedure_id]
#blood_banks = BloodBank.where(:procedure_id => params[:procedure_id])
end
if params[:location_ids]
#blood_banks = BloodBank.where(:location_id.in => params[:location_ids])
end
...
if condition
end
If i need to search Procedure "Discectomy" in location "Hebbal" then i nned to define the if condition as follows,
if params[:procedure_id].present? && params[:location_id].present?
...
end
Then i need to do for all such combinations(4x3x2x1) of search, for my refine search!!!
Which is the best way to implement the same.
How do you achieve above situation???
I can't right all the possible if conditions, is their any shortcut method!!!
How to achieve below code:
if params[:fees].present?
if params[:fees] == "300"
#doctor_clinic = DoctorClinic.where( :consultation_fees => { '$lte' => params[:fees] }).map(&:doctor_id)
#doctors = Doctor.where(
{ :id.in => #doctor_clinic })
end
if params[:fees] == "500"
#doctor_clinic = DoctorClinic.where( :consultation_fees => { '$gte' => 300, '$lte' => params[:fees] }).map(&:doctor_id)
#doctors = Doctor.where(
{ :id.in => #doctor_clinic })
end
if params[:fees] == "1000"
#doctor_clinic = DoctorClinic.where( :consultation_fees => { '$gte' => 500, '$lte' => params[:fees] }).map(&:doctor_id)
#doctors = Doctor.where(
{ :id.in => #doctor_clinic })
end
if params[:fees] == "1001"
#doctor_clinic = DoctorClinic.where( :consultation_fees => { '$gte' => params[:fees] }).map(&:doctor_id)
#doctors = Doctor.where(
{ :id.in => #doctor_clinic })
end
end
You can do this:
conditions = {}
conditions.merge!(:procedure_id => params[:procedure_id]) if params[:procedure_id]
conditions.merge!(:location_id.in => params[:location_ids]) if params[:location_ids]
...
#blood_banks = BloodBank.where(conditions)
EDIT:
Regarding your last code, since you have no logic here (common idea for all values), you can use case:
condition = case params[:fees]
when "300"
{ '$lte' => 300 }
when "500"
{ '$gte' => 300, '$lte' => 500 }
when "1000"
{ '$gte' => 500, '$lte' => 1000 }
when "1001"
{ '$gte' => 1001 }
else
nil
end
if condition
#doctor_clinic = DoctorClinic.where( :consultation_fees => condition).map(&:doctor_id)
#doctors = Doctor.where({ :id.in => #doctor_clinic })
end

Error "No Method" when using delayed job

I'm trying to import 90k lines of xml into my ruby app. herokus timeout limit is 30s so i'm trying to use delayed job.
The import class works wonderfully in around 48-hippopotomuses locally. When i add the line
handle_asynchronously :save_races
I get the error "undefined method save_races' for classXmltube'"
What am i doing wrong with DJ and how can i get this to work?
Full class code below
require "rexml/document"
class Xmltube
def self.convert_save(xml_data)
doc = REXML::Document.new xml_data.read
doc.elements.each("Meeting") do |meeting_element|
meeting = save_meeting(meeting_element)
save_races(meeting_element, meeting)
Rails.logger.info "all done"
end
end
def self.save_races(meeting_element, meeting)
meeting_element.elements.each("Races/Race") do |race_element|
race = save_race(race_element, meeting)
save_race_entrants(race_element, race)
end
end
def self.save_race_entrants(race_element, race)
race_element.elements.each("RaceEntries/RaceEntry") do |entry_element|
horse = save_horse(entry_element)
jockey = save_jockey(entry_element)
start = save_start(entry_element, horse, jockey, race)
save_sumaries(entry_element, start)
end
end
def self.save_track(meeting_element)
# there is only one track, but still, each? wtf.
t = {}
meeting_element.elements.each("Track") do |track|
t = {
:name => track.attributes["VenueName"],
:track_code => track.attributes["VenueCode"],
:condition => track.elements['TrackRating'].text,
:club_id => save_club(meeting_element.elements["Club"]).id
}
end
track = Track.where(:track_code => t[:track_code] ).first
if track
Track.update(track.id, t)
else
Track.create(t)
end
end
def self.save_meeting meeting_element
t = {
:meet_code => meeting_element.attributes['MeetCode'],
:stage => meeting_element.elements["MeetingStage"].text,
:phase => meeting_element.elements["MeetingPhase"].text,
:nominations_close_at => meeting_element.elements["NominationsClose"].text,
:acceptance_close_at => meeting_element.elements["AcceptanceClose"].text,
:riders_close_at => meeting_element.elements["RidersClose"].text,
:weights_published_at => meeting_element.elements["WeightsPublishing"].text,
:club_id => save_club(meeting_element.elements["Club"]).id ,
:track_id => save_track(meeting_element).id,
:tab_status => meeting_element.elements["TabStatus"].text,
:state => meeting_element.elements["StateDesc"].text,
:day_night => meeting_element.elements["DayNight"].text,
:number_of_races => meeting_element.elements["NumOfRaces"].text,
:meet_date => meeting_element.elements["MeetDate"].text,
}
meeting = Meeting.where(:meet_code => t[:meet_code] ).first
if meeting
Meeting.update(meeting.id, t)
else
Meeting.create(t)
end
end
############################################################
def self.save_sumaries entry_element, start
entry_element.elements.each('Form/ResultsSummaries/ResultsSummary') do | element |
s = {
:name => element.attributes['Name'],
:start_id => start.id,
:starts => element.attributes['Starts'],
:wins => element.attributes['Wins'],
:seconds => element.attributes['Seconds'],
:thirds => element.attributes['Thirds'],
:prize_money => element.attributes['PrizeMoney'],
}
sum = Summary.where(:name => s[:name] ).where(:start_id => s[:start_id]).first
if sum
Summary.update(sum.id, s)
else
Summary.create(s)
end
end
end
def self.save_start entry_element, horse, jockey, race
s = {
:horse_id => horse.id,
:jockey_id => jockey.id,
:race_id => race.id,
:silk => entry_element.elements["JockeySilksImage"].attributes["FileName_NoExt"],
:start_code => entry_element.attributes['RaceEntryCode'],
:handicap_weight => entry_element.elements['HandicapWeight'].text,
}
# Rails.logger.info entry_element['HandicapWeight'].text
start = Start.where(:start_code => s[:start_code] ).first
if start
Start.update(start.id, s)
else
Start.create(s)
end
end
def self.save_jockey entry_element
j={
:name => entry_element.elements['JockeyRaceEntry/Name'].text,
:jockey_code => entry_element.elements['JockeyRaceEntry'].attributes["JockeyCode"],
}
jockey = Jockey.where(:jockey_code => j[:jockey_code] ).first
if jockey
Jockey.update(jockey.id, j)
else
Jockey.create(j)
end
end
def self.save_horse entry_element
trainer = save_trainer entry_element
h= {
:name => entry_element.elements['Horse'].attributes["HorseName"],
:color => entry_element.elements['Horse'].attributes["Colour"],
:dob => entry_element.elements['Horse'].attributes["FoalDate"],
:sex => entry_element.elements['Horse'].attributes["Sex"],
:trainer_id => trainer.id,
:horse_code => entry_element.elements['Horse'].attributes["HorseCode"],
}
horse = Horse.where(:horse_code => h[:horse_code] ).first
if horse
Horse.update(horse.id, h)
else
Horse.create(h)
end
end
def self.save_trainer entry_element
t= {
:name => entry_element.elements['Trainer/Name'].text,
:trainer_code => entry_element.elements['Trainer'].attributes["TrainerCode"]
}
trainer = Trainer.where(:trainer_code => t[:trainer_code] ).first
if trainer
Trainer.update(trainer.id, t)
else
Trainer.create(t)
end
end
def self.save_club element
t = {}
t = {
:club_code => element.attributes['ClubCode'],
:title => element.attributes["Title"],
}
club = Club.where(:club_code => t[:club_code] ).first
if club
Club.update(club.id, t)
else
Club.create(t)
end
end
def self.save_race element, meeting
r = {
:name => element.elements['NameRaceFull'].text,
:occur => element.elements['RaceStartTime'].attributes["TimeAtVenue"],
:distance => element.elements['RaceDistance'].text,
:race_type => element.elements['RaceType'].text,
:track_id => meeting.track_id,
:race_code => element.attributes["RaceCode"],
:meeting_id => meeting.id
}
race = Race.where(:race_code => r[:race_code] ).first
if race
Race.update(race.id, r)
else
Race.create(r)
end
end
handle_asynchronously :save_races
end
Since your save_races is a class method, you should call handle_asynchronously on Xmltube's singleton class:
class << self
handle_asynchronously :save_races
end
This just worked as I would expect
class Foo
def self.bar(s)
Rails.logger.info "From Foo.bar('#{s}')"
end
end
# then ...
Foo.delay.bar('hello')
I was running 4.0.4 of DJ with ruby 2.1

Resources