Activerecord map to array - ruby-on-rails

I'm trying to take everything out of my Users table and send it to mail chimp for subscription.
I need to go from User.all to
[{:email => {:email => "example#domain.org"},
:merge_vars => {:FNAME => "First name", :LNAME => "Last name"}
}]
I'm trying to do this with map but I'm struggling, any ideas of the cleanest way of doing this?

subscription_array = User.all.collect do |user|
{
:email => {:email => user.email},
:merge_vars => {:FNAME => user.first_name, :LNAME => user.last_name}
}
end

users_array = []
User.all.find_each {|u| users_array << {:email => u.email, :merge_vars => {:FNAME => u.first_name, :LNAME => u.last_name} }
I chose to use find_each is it's a more efficient way of loading your collection.
http://api.rubyonrails.org/classes/ActiveRecord/Batches.html

Related

Ruby - Stripe: Missing required param: type

I am trying to add a bank account using Ruby stripe API. but it gives the stripe error "Missing required param: type".
I am using following ruby code:
account = Stripe::Account.create({
:country => 'US',
:managed => true,
:transfer_schedule => {
:interval => 'weekly',
:weekly_anchor => 'friday'
},
:legal_entity => {
:dob => {
:day => birthday.day,
:month => birthday.month,
:year => birthday.year
},
:first_name => first_name,
:last_name => last_name,
:type => 'individual'
},
:tos_acceptance => {
:date => Time.now.to_i,
:ip => request.remote_ip
}
})
You are not passing the proper parameters to the API.
Please check this document for the proper request and response returned by Stripe.
https://stripe.com/docs/api?lang=ruby#create_account
require "stripe"
Stripe.api_key = "sk_test_bcd1234"
Stripe::Account.create(
:type => 'standard',
:country => 'US',
:email => 'bob#example.com'
)
To point out you are not passing :type param in the outer hash. You need to move it to the first level.
account = Stripe::Account.create(
{
:country => 'US',
:managed => true,
:type => 'individual', # Move this from nested to first level
:transfer_schedule => {
:interval => 'weekly',
:weekly_anchor => 'friday'
},
:legal_entity => {
:dob => {
:day => birthday.day,
:month => birthday.month,
:year => birthday.year
},
:first_name => first_name,
:last_name => last_name
},
:tos_acceptance => {
:date => Time.now.to_i,
:ip => request.remote_ip
}
}
)

API POST with array using HTTP gem (or RestClient)

I'm having trouble with this api and can't seem to get over the hump. Using the HTTP gem (though I'm flexible and can use RestClient if that gets me an answer quicker!). Anyway, I'm having trouble posting an array. everything else is good, I just can't figure out this "itemsarray" in the printaura api found here in the addorder method: PrintAura API
I'm running this:
def self.submitorder
req = HTTP.post("https://api.printaura.com/api.php", :json => {
:key => APIKEY,
:hash => APIHASH,
:method => "addorder",
:businessname => "this is a secret too",
:businesscontact => "thats a secret",
:email => "my#email.com",
:your_order_id => "1",
:returnlabel => "FakeAddress",
:clientname => "ShippingName",
:address1 => "ShippingAddressLine1",
:address2 => "ShippingAddressLine2",
:city => "ShippingCity",
:state => "ShippingState",
:zip => "ShippingZip",
:country => "US",
:customerphone => "dontcallme",
:shipping_id => "1",
:itemsarray => {:item => [
:product_id => 423,
:brand_id => 33,
:color_id => 498,
:size_id => 4,
:front_print => 1389517,
:front_mockup => 1390615,
:quantity => 1
]}
})
puts JSON.parse(req)
end
And my output is this:
{"status"=>false, "error_code"=>19, "result"=>19, "message"=>"You cannot place an order without items, Please fill the items array with all the required information. Full API documentation can be found at https:/www.printaura.com/api/"}
Gosh, if someone could look at that and help me out I would forever appreciate it.
def self.submitorder
itemsarray = { :items => [ { :product_id => 423, :brand_id => 33, :color_id => 498, :size_id => 4, :quantity => 1, :front_print => 1389517,
:front_mockup => 1390617 } ] }
req = HTTP.post("https://api.printaura.com/api.php", :json => {
:key => APIKEY,
:hash => APIHASH,
:method => "addorder",
:businessname => "this is a secret too",
:businesscontact => "thats a secret",
:email => "my#email.com",
:your_order_id => "1",
:returnlabel => "FakeAddress",
:clientname => "ShippingName",
:address1 => "ShippingAddressLine1",
:address2 => "ShippingAddressLine2",
:city => "ShippingCity",
:state => "ShippingState",
:zip => "ShippingZip",
:country => "US",
:customerphone => "dontcallme",
:shipping_id => "1",
:items => Base64.encode64(itemsarray.to_json)}
)
puts JSON.parse(req)
I really hopes this helps somebody some years from now haha
To create a array in JSON you use an array in Ruby. Its that easy.
require 'json'
def self.submitorder
req = HTTP.post("https://api.printaura.com/api.php", :json => {
:key => APIKEY,
:hash => APIHASH,
:method => "addorder",
:businessname => "this is a secret too",
:businesscontact => "thats a secret",
:email => "my#email.com",
:your_order_id => "1",
:returnlabel => "FakeAddress",
:clientname => "ShippingName",
:address1 => "ShippingAddressLine1",
:address2 => "ShippingAddressLine2",
:city => "ShippingCity",
:state => "ShippingState",
:zip => "ShippingZip",
:country => "US",
:customerphone => "dontcallme",
:shipping_id => "1",
:items => [
{
:product_id => 423,
:brand_id => 33,
:color_id => 498,
:size_id => 4,
:front_print => 1389517,
:front_mockup => 1390615,
:quantity => 1
}
]
})
puts JSON.parse(req)
The API lists a items parameter which should contain an array of objects. It says nothing about itemsarray.

how to do ccavenuee payment gateway integration in rails

I tried ccavenue but I'am getting this error. paypal is working fine.
undefined methodpayment_service_for'`
This is my controller action
def create
#subscription = Subscription.new(subscription_params)
#programme = Programme.find(subscription_params[:programme_id])
rand_number = rand.to_s[2..11]
#programme.update_attributes(:invoice_id => rand_number)
session[:programme_id]=#programme.id
session[:invoice_id]=#programme.invoice_id
#paypal = PaypalPayment.create(:material_type => 'Programmes',:invoice_id => rand_number,:currency => #programme.currency, :status => 'Processing', :created_at => DateTime.now, :user_id => current_user.specific.id, :email_id => current_user.specific.email, :programme_id => #programme.id,:amount => #programme.price_paisas)
#paypal.save
`session[:paypal_id]=#paypal.id
logger.info #programme.inspect
if subscription_params[:payment_type] == 'paypal'
item_details=[]
if #programme.currency == 'INR'
price = #programme.price.exchange_to('USD')
else
price = #programme.price
end
logger.info price.inspect
item_details << {:name => #programme.title, :quantity => '1', :amount => price.fractional}
response = EXPRESS_GATEWAY.setup_purchase(price.fractional,
:items => item_details,
:currency => "USD",
:order_id => #programme.invoice_id,
:return_url => students_success_url,
:cancel_return_url => students_root_url
)
logger.info response.inspect
session[:programme_price]=price
return redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token)
elsif subscription_params[:payment_type] == 'ccavenue'
payment_service_for #programme.invoice_id, CCAVENUE_ACCOUNT,
:amount => #programme.price.fractional,
:currency => 'INR',
:service => :ccavenue do |service|
service.customer :name => current_user.name,
:email => current_user.email,
:phone => current_user.mobile
service.redirect :return_url => students_success_url
submit_tag 'Proceed to payment'
end
end
end
end`
I referred this link:
https://github.com/meshbrain/active_merchant_ccavenue
The payment_service_for is the view helper of the Active Merchant gem. You should use this method inside views or you should include view helpers inside your controller.

How to get the country and state from a paypal transaction?

I would like to know how to obtain the country and state, from the billing address, in a paypal transaction.
So far I can get a transaction object via the code below:
# ...
def self.paypal_transaction_details(txn_id)
#api = PayPal::SDK::Merchant.new
get_transaction_details = #api.build_get_transaction_details({:TransactionID => txn_id })
response = #api.get_transaction_details(get_transaction_details)
end
Is it possible to get the location info? Or should I use geocoder to get the country and state from the ip address?
Reference: https://github.com/paypal/merchant-sdk-ruby
Response:
response.PaymentTransactionDetails.PayerInfo.Address
=> #<PayPal::SDK::Merchant::DataTypes::AddressType:0x007fd58f604660 #AddressOwner="PayPal", #AddressStatus="None">
Thanks in advance
I am not sure if you are using this gem 'paypal-sdk-rest'
but if you are, when you Create Payment
you can do
require 'paypal-sdk-rest'
include PayPal::SDK::REST
PayPal::SDK::REST.set_config(
:mode => "sandbox", # "sandbox" or "live"
:client_id => "EBWKjlELKMYqRNQ6sYvFo64FtaRLRR5BdHEESmha49TM",
:client_secret => "EO422dn3gQLgDbuwqTjzrFgFtaRLRR5BdHEESmha49TM")
# Build Payment object
#payment = Payment.new({
:intent => "sale",
:payer => {
:payment_method => "credit_card",
:funding_instruments => [{
:credit_card => {
:type => "visa",
:number => "4567516310777851",
:expire_month => "11",
:expire_year => "2018",
:cvv2 => "874",
:first_name => "Joe",
:last_name => "Shopper",
:billing_address => {
:line1 => "52 N Main ST",
:city => "Johnstown",
:state => "OH",
:postal_code => "43210",
:country_code => "US" }}}]},
:transactions => [{
:item_list => {
:items => [{
:name => "item",
:sku => "item",
:price => "1",
:currency => "USD",
:quantity => 1 }]},
:amount => {
:total => "1.00",
:currency => "USD" },
:description => "This is the payment transaction description." }]})
# Create Payment and return the status(true or false)
if #payment.create
#payment.id # Payment Id
else
#payment.error # Error Hash
end
I hope that this helps.
ps.
you have to request the info first, if not there would be nil or '' when you want to get them back

create_or_update method in rails

if ClassName.exists?(["id = ?", self.id])
object = ClassName.find_by_name(self.name)
object.update_attributes!( :street_address => self.street_address,
:city_name => self.city_name,
:name => self.org_unit_name,
:state_prov_id => self.state_prov_id,
:zip_code => self.zip_code)
else
ClassName.create! :street_address => self.street_address,
:city_name => self.city_name,
:federalid => self.federalid,
:name => self.org_unit_name,
:state_prov_id => self.state_prov_id,
:zip_code => self.zip_code
end
I have code like this. I would like to improve it so that it uses a method, something like create_or_update.
ClassName.create_or_update_by_name(:name => self.name,
:street_address => self.street_address,
:city_name => self.city_name,
:federalid => self.federalid,
:name => self.org_unit_name,
:state_prov_id => self.state_prov_id,
:zip_code => self.zip_code)
If the name exists in the database then it should update that object otherwise it should create a new object.
Is there is any method that exists that I can do this with?
my_class = ClassName.find_or_initialize_by_name(name)
my_class.update_attributes(
:street_address => self.street_address,
:city_name => self.city_name,
:federalid => self.federalid,
:state_prov_id => self.state_prov_id,
:zip_code => self.zip_code
)
As of Rails 6, update_attributes! and update_attributes is deprecated for update! and update, respectively:
my_class.update(
:street_address => self.street_address,
:city_name => self.city_name,
:federalid => self.federalid,
:state_prov_id => self.state_prov_id,
:zip_code => self.zip_code
)
The checked answer above works well for Rails 3. That said the find_or_initialize_by_attribute methods were deprecated in Rails 4. This is the new way. See Rails4 Deprecation warning for find_or_initialize_by method
person = Person.find_or_initialize(name: 'name')
person.update_attributes(other_attrs)
person = Person.find_by_name(name) || Person.new(:name => name)
person.update_attributes!(:street_address => street_address, :city_name => city_name) #etc etc

Resources