What does this rails condition do? - ruby-on-rails

In my rails app I have this piece of code:
def get_auth_token
if auth_token = params[:auth_token].blank? && request.headers["auth_token"]
params[:auth_token] = auth_token
end
end
Can someone explain the if statement and what happens here? I'm not too fluent in ROR so I'm having a hard time figuring this syntax out.

The first answer is incorrect. Your code can be roughly translated into this:
if params[:auth_token].blank?
params[:auth_token] = request.headers["auth_token"]
end
That is, if "auth_token" in params is blank it is set to "auth_token" from headers.
It isn't set only to true because boolean operators do not return singleton booleans in Ruby:
true && "abcde" #=> "abcde"
nil || 42 #=> 42
nil && nil #=> nil
I only omitted one conditional from your code, here goes the complete translation:
if params[:auth_token].blank? and request.headers["auth_token"]
params[:auth_token] = request.headers["auth_token"]
end
The only difference is when params[:auth_token] = "" and request.headers["auth_token"] = nil the parameter won't change to nil. Which is a very minor thing I'm not sure if you care about this.
If there weren't any blank strings involved, you could express it more clear with Ruby's "or equal" operator:
params[:auth_token] ||= request.headers["auth_token"]

Here is a description:
def get_auth_token
if auth_token = params[:auth_token].blank? && request.headers["auth_token"]
# sets the var auth_token to true/false inside the IF statement to
# true IF params[:auth_token] is empty or nil AND
# request.headers["auth_token"] is not nil (but could be empty)
params[:auth_token] = auth_token
# set the params[:auth_token] to auth_token (which could only be true)
end
end
That means, in human language:
If the request sent an empty params[:auth_token] (or none) AND the
HTTP request contains in its headers a value (could be empty) for the key "auth_token",
it will set the params[:auth_token] to true;
The longer version:
def get_auth_token
auth_token = ( params[:auth_token].blank? && request.headers["auth_token"] ) # can be true/false
if auth_token
params[:auth_token] = auth_token
end
end
The shorter version (you could refactor your code to this):
def get_auth_token
params[:auth_token] = true if params[:auth_token].blank? && request.headers["auth_token"].present?
end

Related

updating the database after create action doesn't work

set_bonus(member_id, cookie) method does not work. I'm trying to update the same model that that the self.set_signup_attribution(member_id, cookie, origin) returns.
The new_has_value variable returns {"currency"=>"usd", "type"=>"flat", "amount"=>1000}
Model.rb
# THIS METHOD WORKS
def self.set_signup_attribution(member_id, cookie, origin)
return unless cookie.present?
tracking_code = cookie
attribution_channel = AttributionChannel.find_by tracking_code: tracking_code
associated_member_record = Member.find member_id
if attribution_channel.present?
Attribution.create!({
event: Attribution::SIGN_UP,
attribution_channel: attribution_channel,
associated: associated_member_record,
extra: origin
})
set_bonus(member_id, cookie)
else
Rails.logger.info "Unknown Attribution Channel for tracking code: '#{ tracking_code }'"
end
end
# THIS METHOD DOES NOT WORK. UPDATES THE DATABASE.
def self.set_bonus(member_id, cookie)
epoch = Member.find_by(id: member_id).attribution_epoch
attribution_code = AttributionChannel.find_by(tracking_code: cookie)
duration_value = attribution_code.attribution_duration.downcase.split(' ')
duration = duration_value.first.to_i.send(duration_value.last)
return if cookie.present? && epoch.present?
current_time = Time.now
if attribution_code.bonus_config.present?
if (current_time - epoch).to_i < duration
hash_value = attribution_code.bonus_config
new_hash_value = hash_value.assoc("sign_up")[1]
value = Attribution.where(attribution_channel_id: attribution_code)
if new_hash_value["type"] == "flat"
value.update_all(
bonus_amount: new_hash_value["amount"],
bonus_currency: new_hash_value["currency"]
)
elsif new_hash_value["type"] == "percentage"
value.update_all(
bonus_amount: new_hash_value["amount"],
bonus_currency: new_hash_value["currency"]
)
else
{
bonus_amount: "Doesn't exist",
bonus_currency: "Doesn't exist"
}
end
else
"Do nothing"
end
else
"Do nothing"
end
#cookie = nil
binding.pry
end
Controller.rb
def index
unless session[:just_signed_up]
redirect_back_or_settings_page
end
Attribution.set_signup_attribution(current_user, cookies[:visit_attr], request.referer)
Attribution.set_bonus(current_user, cookies[:visit_attr])
session[:just_signed_up] = false
#email = current_user.email
end
How do I go about this? That is what I have tried and doesn't work. Can I merge set_bonus method to set_signup_attribution method or something?
Any help will be appreciated.
So drilling this further:
I merged set_bonus with set_signup_attribution and the two fields (bonus_amount and bonus_currency) which set_bonus method is supposed to update returns nil:
Attribution.create!(
{
event: Attribution::SIGN_UP,
attribution_channel: attribution_channel,
associated: associated_member_record,
extra: origin
}.merge(self.set_bonus(member_id, cookie).to_h)
)
With this drill after using binding.pry on that set_bonus method, I figured out it worked but it's returning nil and I don't know why. Could it be because member_id is not available in the model or something?
in your if statement you should call set_bonus method on appropriate object.
attribution = Attribution.create!({
event: Attribution::SIGN_UP,
attribution_channel: attribution_channel,
associated: associated_member_record,
extra: origin
})
attribution.set_bonus(member_id, cookie) if attribution.persisted?
Just be careful as .create! will raise an error in case there is something wrong, so maybe would be better to use
attribution = Attribution.new(.....)
if attribution.save
attribution.set_bonus(.....)
else
Rails.logger.info attribution.errors
end
I hope this would help.
Cheers

Rails logic not firing on `false` results

Receiving as an API an array of hashes
#request['clients'].each do |client|
validations are being executed on each clientattributes. However, rails logic is failing to fire up on false statements and this ignoring them. Example validation:
def client_type_ok
if #this_client['type'] == "ADT" || #this_client['type'] == "CHD"
true
else
false
#error_code_39 = true
end
end
The controller action wants to execute only when true conditions are met:
if client_type_ok && client_type_ok
However Rails.logger is clearly confirming that this condition is being passed through although false.
Rails.logger.info !#this_client['type'].blank?
Rails.logger.info #this_client['type']
Rails.logger.info "not"
Rails.logger.info #this_client['type'] != "ADT"
Rails.logger.info "ADT"
Rails.logger.info #this_client['type'] == "ADT"
is returning
true
APT
not
true
ADT
` `
The bottom is generated as a blank. The same occurs replacing Rails.logger with p. All logic of this action is ignoring false results. While I can attempt to devise processing cases of fully true cases, this is inconvenient and counter-intuitive.
Thus, there appears to be a meta function which is impeding the handling of false cases. How can this be tracked down? Can Rails.logger logic be step traced?
You're not returning false there
def client_type_ok
if #this_client['type'] == "ADT" || #this_client['type'] == "CHD"
true
else
false # this is not doing anything. Simply ignored.
#error_code_39 = true # result of this assignment will be true.
# and it also is the last expression of the if
# so it becomes the implicit return value of the method
end
end
def client_type_ok
if #this_client['type'] == "ADT" || #this_client['type'] == "CHD"
true
else
false
#error_code_39 = true
end
end
As Sergio mentiond in the above answer,The return value of yur method will be true for the else condtion. You need to swap the places or You can rewrite the above method
def client_type_ok
return true if %w(ADT CHD).include?(#this_client['type'])
#error_code_39 = true
false
end

Ruby how to modify parameters

so i have this code that and my aim was to convert any empty string to null
def convert_empty_strings_to_null
if request.patch? || request.post?
convert_empty_strings_to_null_rec(request.params)
end
end
def convert_empty_strings_to_null_rec(param)
param = nil if param.empty? if param.is_a?(String)
param.all?{|v| convert_empty_strings_to_null_rec v} if param.is_a?(Array)
param.all?{|k,v| convert_empty_strings_to_null_rec v} if param.is_a?(Hash)
end
But i'm new to ruby on rails and i found it that it sends params by value and not by reference, so no change in params is made, how do i fix this ?
I assume that by "empty" you mean zero-with strings, meaning that strings consisting only of whitespace should be left intact. (Otherwise blank? and strip would be your friends.)
def convert_empty_strings_to_nil
if request.patch? || request.post?
request.params.each do |key, value|
request.params[key] = convert_empty_strings_to_nil_rec(value)
end
end
end
def convert_empty_strings_to_nil_rec(param)
case param
when String
param.empty? ? nil : param
when Array
param.map{ |v| convert_empty_strings_to_nil_rec(v) }
when Hash
param.map{ |k,v| [k, convert_empty_strings_to_nil_rec(v)] }.to_h
else
param
end
end
First of all, this is how your convert_empty_strings_to_null_rec method should be, for keeping the changes persistent:
def convert_empty_strings_to_null_rec(param)
if param == ""
updated_param == nil
elsif param.is_a?(Array)
updated_param == param.map{|x| nil if x.empty? }
elsif param.is_a?(Hash)
updated_param = {}
param.each do |k, v|
if v.empty?
updated_param[k] = nil
else
updated_param[k] = v
end
end
end
return updated_param
end
Further, I am assuming from your question that convert_empty_strings_to_null is a action method. It should be updated to catch what convert_empty_strings_to_null_rec method is returning.
def convert_empty_strings_to_null
if request.patch? || request.post?
updated_params = convert_empty_strings_to_null_rec(request.params)
end
# you can use the updated_params here on in this action method
end
Hope it helps : )

How to test a specific line in a rails model using rspec

I have a model with an initializer in it, which basically creates a user from a user hash.
After it gets the user information, it checks whether the "privileges" key in the hash is an array. If it's not, it turns it into an array.
Now the obvious way of doing this would be crafting an entire user_hash so that it would skip those "create user" lines and then check if it turns the input into an array if necessary. However, I was wondering if there is a more DRY way of doing this?
Here is the user model I'm talking about:
def initialize(opts={})
#first_name = opts[:user_hash][:first]
#last_name = opts[:user_hash][:last]
#user_name = opts[:user_hash][:user_name]
#email = opts[:user_hash][:email]
#user_id = opts[:user_hash][:id]
#privileges = {}
if opts[:privs].present?
if !opts[:privs].kind_of?(Array)
opts[:privs] = [opts[:privs]]
end
end
end
You can pass a double which returns the needed value when the proper key is requested, and itself (or something else) otherwise:
it 'turns privs into an array' do
opts = double(:opts)
allow(opts)to receive(:[]).and_return(opts)
allow(opts)to receive(:[]).with(:privs).and_return('not array')
expect(MyClass.new(opts).privileges).to eq(['not array'])
end
Btw, your code could be simplified using the splat operator:
privs = [*opts[:privs]]
sample behavior:
privs = nil
[*privs]
# => []
privs = ['my', 'array']
[*privs]
# => ["my", "array"]
privs = 'my array'
[*privs]
# => ["my array"]
You can even use the idempotent Kernel#Array
def initialize(opts = {})
#first_name = opts[:user_hash][:first]
#last_name = opts[:user_hash][:last]
#user_name = opts[:user_hash][:user_name]
#email = opts[:user_hash][:email]
#user_id = opts[:user_hash][:id]
#privileges = {}
Array(opts[:privs])
end
I hope that helps
Rather than testing the implementation (value is turned into an array), I would test the desired behavior (takes single privilege or multiple privileges):
describe User do
describe '#initialize' do
it "takes single privilege" do
user = User.new(user_hash: {}, privs: 'foo')
expect(user.privileges).to eq(['foo'])
end
it "takes multiple privileges" do
user = User.new(user_hash: {}, privs: ['foo', 'bar'])
expect(user.privileges).to eq(['foo', 'bar'])
end
end
end

inject method to retrieve data from hash

I'm having trouble getting the method below in my user model to handle a hash ('auth') I'm getting from LinkedIn for user signin:
def self.deep_get auth, *fields
auth.inject(auth) { |acc, e| acc[e] if acc }
end
I call the 'deep_get' method later in my user model as I create a user using omniauth/linkedin gem. However, it's returning nil values for the provider/uid/headline/email user fields that I know are not nil.
I included first_name and last_name fields as an example because this approach is working (not returning nil values), but (as I realize) bad style/exception handling. Any ideas as to why my deep_get inject method isn't working to retrieve the data in the hash as I'd like it to?
def self.create_from_omniauth(auth)
create! do |user|
# i'd like to retrieve user information from linkedin per the following with my inject method, but i am getting nil values when i should be getting data.
# :provider and :uid are on the same branch level of data. first_name,last_name,email,etc. are on a branch just below called 'info'
user.provider = deep_get(auth, :provider)
user.uid = deep_get(auth, :uid)
user.headline = deep_get(auth, :info, :headline)
user.email = deep_get(auth, :info, :email)
# the below is working but i know pokemon exception handling is not good style.
begin
user.first_name = auth["info"]["first_name"]
rescue
end
begin
user.last_name = auth["info"]["last_name"]
rescue
end
try this
def deep_find(obj,key)
if obj.respond_to?(:key?) && obj.key?(key)
obj[key]
elsif obj.respond_to?(:each)
r = nil
obj.find{ |*a| r=deep_find(a.last,key) }
r
end
end
or try this
class Hash
def deep_fetch(key, default = nil)
default = yield if block_given?
(deep_find(key) or default) or nil
end
def deep_find(key)
if key?(key)
self[key]
else
self.values.inject(nil) do |memo, v|
memo = v.deep_find(key) if v.respond_to?(:deep_find)
memo unless memo.nil?
end
end
end
end

Resources