How to distinguish between Rails and Rake at the initializers level? - ruby-on-rails

Whether I execute rails or rake, the code present in the initializers folder will be executed. What I want to do is to make sure that the code in a given initializer file doesn't get fired up when running a rake task (hence only when Rails server or console are launched).
For example, I'd like to be able to do something like (in config/initializers/blabla.rb):
do_something # code always executed
unless ENV['rake']
something_when_not_rake # code executed only if rails server or console
end
do_something_more # more code always executed
I've been looking into the ENV variable to see what's available there but I've seen nothing interesting, here's the content (in the format "key" => "value"):
"rvm_bin_path" => "/Users/lucke84/.rvm/bin"
"GEM_HOME" => "/Users/lucke84/.rvm/gems/ruby-2.2.3"
"SHELL" => "/bin/bash"
"TERM" => "xterm-256color"
"TMPDIR" => "/var/folders/73/q8t0jjrx3zb8zvd072dgq11c0000gn/T/"
"IRBRC" => "/Users/lucke84/.rvm/rubies/ruby-2.2.3/.irbrc"
"Apple_PubSub_Socket_Render" => "/private/tmp/com.apple.launchd.mF5Uh4NPbk/Render"
"MY_RUBY_HOME" => "/Users/lucke84/.rvm/rubies/ruby-2.2.3"
"USER" => "lucke84"
"rvm_stored_umask" => "0022"
"_system_type" => "Darwin"
"rvm_path" => "/Users/lucke84/.rvm"
"SSH_AUTH_SOCK" => "/private/tmp/com.apple.launchd.ryhqrdVtVU/Listeners"
"__CF_USER_TEXT_ENCODING" => "0x1F5:0x0:0x0"
"rvm_prefix" => "/Users/lucke84"
"PATH" => "/Users/lucke84/.rvm/gems/ruby-2.2.3/bin:/Users/lucke84/.rvm/gems/ruby-2.2.3#global/bin:/Users/lucke84/.rvm/rubies/ruby-2.2.3/bin:/Users/lucke84/.rvm/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/apache-maven/apache-maven-3.3.1/bin"
"rvm_loaded_flag" => "1"
"PWD" => "/Users/lucke84/projects/website"
"JAVA_HOME" => "/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home"
"XPC_FLAGS" => "0x0"
"_system_arch" => "x86_64"
"_system_version" => "10.11"
"XPC_SERVICE_NAME" => "0"
"rvm_version" => "1.26.11 (latest)"
"HOME" => "/Users/lucke84"
"SHLVL" => "1"
"rvm_ruby_string" => "ruby-2.2.3"
"LOGNAME" => "lucke84"
"LC_CTYPE" => "en_US.UTF-8"
"GEM_PATH" => "/Users/lucke84/.rvm/gems/ruby-2.2.3:/Users/lucke84/.rvm/gems/ruby-2.2.3#global"
"rvm_delete_flag" => "0"
"RUBY_VERSION" => "ruby-2.2.3"
"_system_name" => "OSX"
"rvm_user_install_flag" => "1"
"BUNDLE_GEMFILE" => "/Users/lucke84/projects/website/Gemfile"
"_ORIGINAL_GEM_PATH" => "/Users/lucke84/.rvm/gems/ruby-2.2.3:/Users/lucke84/.rvm/gems/ruby-2.2.3#global"
"BUNDLE_BIN_PATH" => "/Users/lucke84/.rvm/gems/ruby-2.2.3/gems/bundler-1.10.6/bin/bundle"
"RUBYOPT" => "-rbundler/setup"
"RUBYLIB" => "/Users/lucke84/.rvm/gems/ruby-2.2.3/gems/bundler-1.10.6/lib"
"MANPATH" => "/Users/lucke84/.rvm/gems/ruby-2.2.3/gems/unicorn-5.0.1/man"
I cannot find a built-in environment key/value to programmatically determine who is triggering the command. Maybe one of you can shed some light on this topic for me?
Further details:
this cannot be an environment-dependent check, it should work for development as well as for production (or whatever the environment)
I would like to avoid to specify a custom parameter (i.e. bin/rake my:task skip_initializer=true), as what I'm trying to do is to skip that initializer's executions for all rake tasks
running Rails 4.2.x at the moment
Thanks in advance for your help!

Related

MongoDB update and increment operation, when update data is an empty hash

When using Ruby-on-Rails with ruby version 2.2.0, MongoDB version 3.0.5,
I am experiencing a weird behaviour when trying to execute an update query contains both update and increment, when the update data is an empty hash:
When running the command:
(1) db.collection.update({'user_id' => 123456}, {'$set' => {}, '$inc' => { 'counter' => 1 }}, {:upsert => true})
The value of the field counter left as it was (no change).
When running the command:
(2) db.collection.update({'user_id' => 123456}, {'$inc' => { 'counter' => 1 }}, {:upsert => true})
The value of the field counter is incremented by 1, as expected.
Can someone please explain to me why command (1) has a different result than command (2)?
db.collection.update({'user_id' => 123456}, {'$set' => {}, '$inc' => { 'counter' => 1 }}, {:upsert => true})
outputs '$set' is empty. You must specify a field like so: {$mod: {<field>: ...}} exception
This might be the reason why your counter is not incremented.
Which version of mongodb are you using Mine is 2.6

Requiring apt::source as a dependency gives a syntax error

I need to add the docker source list to apt before installing docker.
I have
apt::source { 'debian-jessie':
comment => 'This is the docker Debian jessie mirror',
location => 'http://apt.dockerproject.org/repo',
release => 'debian-jessie',
repos => 'main',
key_content => '58118E89F3A912897C070ADBF76221572C52609D',
key_server => 'keyserver.ubuntu.com',
ensure => present,
include_src => false,
include_deb => true,
}
which works, and also
package {'docker-engine':
ensure => present,
before => Class['docker'],
}
which works only after a second run (I use vagrant provision, but that's not relevant to the problem).
What I would like is making the whole thing work at the first provisioning by instructing puppet to execute apt::source before docker-engine, however adding it in require is not a valid syntax:
package {'docker-engine':
ensure => present,
before => Class['docker'],
require => [
Apt::source['debian-jessie'],
]
}
How to specify this dependency?
The rest of the file looks like this:
class { 'docker':
dns => '192.168.1.1',
manage_package => false,
use_upstream_package_source=> false,
# service_name => 'docker',
docker_command => 'docker',
package_name => 'docker-engine',
service_enable => true,
service_state => 'running',
extra_parameters => ["--insecure-registry=192.168.1.0/24"],
}
include 'docker'
file { "/lib/systemd/system/docker.service":
notify => Service["docker"],
ensure => present,
owner => "root",
group => "root",
mode => 0600,
source =>"puppet:///modules/docker/etc/systemd/system/docker.service"
} ~> Exec['systemctl-daemon-reload']
Capitalize word source
require => Apt::Source['debian-jessie']
Puppet documentation states:
The general form of a resource reference is:
The resource type, capitalized (every segment must be capitalized if
the resource type includes a namespace separator [::])
An opening square bracket
The title of the resource as a string, or a comma-separated list of titles
A closing square bracket

Ruby add_item for eBay

I am attempting to write a ruby on rails app that posts an item to eBay. Cody Fauser/Garry Tan have a gem called ebayApi which is built on top of the ebay gem. When I attempt to post an item, I am getting an error back from ebay that says the condition ID is required for this category. I have found a category that does not require the condition, and I can post to that category. Searching through the eBay API documentation, I have found a tag conditionID under the "item" class. However, in the documentation for ebayAPI, there is no such tag. Looking back at the ebay API documentation, there is an older way to specify condition, using lookup_attributes. I have noted that the return xml is coming in API version 745, and Garry Gan's updated of the ruby interface is running version 609. I have tried using the lookup, and seem to get the same error (condition required). I am using the following code to specify the item:
#ebay = Ebay::Api.new :auth_token => #seller.ebay_token
item = Ebay::Types::Item.new( :primary_category => Ebay::Types::Category.new(:category_id => #ebayTemplate.categoryID),
:title => #ebayTemplate.name,
:description => #ebayTemplate.description,
:location => #ebayTemplate.location,
:start_price => Money.new((#ebayTemplate.startPrice*100).to_d, #ebayTemplate.currency),
:quantity => 1,
:listing_duration => #ebayTemplate.listingDuration,
:country => #ebayTemplate.country,
:currency => #ebayTemplate.currency,
:payment_methods => ['VisaMC', 'PayPal'],
:paypal_email_address => '********#gmail.com',
:dispatch_time_max => 3,
:lookup_attributes => [Ebay::Types::LookupAttribute.new( :name => "Condition", :value => "New")],
# :attribute_sets => [
# Ebay::Types::AttributeSet.new(
# :attribute_set_id => 2919,
# :attributes => [
# Ebay::Types::Attribute.new(
# :attribute_id => 10244,
# :values => [ Ebay::Types::Val.new(:value_id => 10425) ]
# )
# ]
# )
# ],
:shipping_details => Ebay::Types::ShippingDetails.new(
:shipping_service_options => [
# ShippingServiceOptions.new(
# :shipping_service_priority => 2, # Display priority in the listing
# :shipping_service => 'UPSNextDay',
# :shipping_service_cost => Money.new(1000, 'USD'),
# :shipping_surcharge => Money.new(299, 'USD')
# ),
Ebay::Types::ShippingServiceOptions.new(
:shipping_service_priority => 1, # Display priority in the listing
:shipping_service => #ebayTemplate.shipSvc,
:shipping_service_cost => Money.new((#ebayTemplate.shipSvcCost*100).to_d, #ebayTemplate.currency),
:shipping_surcharge => Money.new((#ebayTemplate.shipSurcharge*100).to_d, #ebayTemplate.currency)
)
],
:international_shipping_service_options => [
Ebay::Types::InternationalShippingServiceOptions.new(
:shipping_service => 'USPSPriorityMailInternational',
:shipping_service_cost => Money.new((#ebayTemplate.shipSvcCost*100).to_d, #ebayTemplate.currency),
:shipping_service_priority => 2,
:ship_to_location => #ebayTemplate.shipToLocation
)
]
),
:return_policy => Ebay::Types::ReturnPolicy.new (
:description => 'this product for suckers only!',
:returns_accepted_option => 'ReturnsAccepted'
)
#:condition_id => 1000
)
#response = #ebay.add_item(:item => item)
As you can see, it is just a mutation of the example given by Cody Fauser. The condition_id at the bottom will bring up an error as there is no such attribute. It seems to me there is no facility for this in the gem since the requirement came into existence after the gem was created. I have not been able to find any other gems to connect with ebay. I have also noticed, there are very little complaints about this even though people are still downloading the gem (10 people downloaded it today). I think there are quite a number of people writing for ebay. Is there a key word I am missing to specify the condition? A work around that people have been using? Another gem I have missed?
There is an existing item_conditions_codes.rb in the gem's type directory and only has two values New and Used. Guess you could add more values in there. However still needs mapping to ID's per the updating (and changed from Attributes) method
You have to modify in the gem library in .. ruby/1.8/gems/ebayapi-0.12.0/lib/ebay/types/item.rb
and add the following new lines
# added to allow ConditionID to be pushed into XML
numeric_node :condition_id, 'ConditionID', :optional => true
then in your ruby ebay code use the following convention
:condition_id => 1500,
At least that seems to work for me right now.

rails functional testing issue

When I do
get :inside, :format => :xml, :lat2 => "41", :lng2 => "-73.9", :lat1 => "40", :lng1 => "-74", :category => "girl", :order => "date"
with my routes.rb includes:
get 'images/inside/:lat1/:lng1/:lat2/:lng2/:order/:category', :to => "images#inside"
I get
ActionController::RoutingError: No route matches {:lng1=>"-74", :category=>"girl", :lat2=>"41", :format=>:xml, :lng2=>"-73.9", :order=>"date", :lat1=>"40", :action=>"inside", :controller=>"images"}
But when I do
get :inside, :format => :xml, :lat2 => "41", :lng2 => "-73", :lat1 => "40", :lng1 => "-74", :category => "girl", :order => "date"
it works!
The only difference is the decimal value of lng2.
Note that if routes.rb has no params, it works, but I need those
As far as I can tell, it's because your value has a period. By default, Rails (at least Rails3) routes cannot contain periods. To work around this, see http://avdi.org/devblog/2010/06/18/rails-3-resource-routes-with-dots-or-how-to-make-a-ruby-developer-go-a-little-bit-insane/
I bet the decimal point is making Rails think that there's a format being specified (e.g. .xml or .js).
You might be able to get around it using a regex, something like what's described here: http://zargony.com/2009/05/05/routing-parameters-with-a-dot

Failed to get session options?

I'm trying to switch the session store in Rails 3 by changing the
config/application.rb as following:
config/application.rb
#-----------------------------------
memcache_options = {
:compression => true,
:debug => false,
:namespace => "xx-cache",
:readonly => false,
:urlencode => false
}
CACHE = MemCache.new(memcache_options)
CACHE.servers = ['127.0.0.1:17898']
#check if CACHE is connected
#puts CACHE
config.action_dispatch.session = {
:session_key => '_xx_session',
:secret => 'xx',
:cache => CACHE,
:expires => 900
}
config.action_dispatch.session_store = :mem_cache_store
#-----------------------------------
Memcache server is running. However, when run rails s, i got this
message:
=> Booting WEBrick
=> Rails 3.0.0.beta3 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
Exiting
/usr/lib/ruby/gems/1.9.1/gems/actionpack-3.0.0.beta3/lib/
action_dispatch/middleware/session/mem_cache_store.rb:19:in
`initialize': #<ActionDispatch::Session::MemCacheStore:0xa302950>
unable to find server during initialization. (RuntimeError)
It seems the session options was not passed correctly. But i'm not
sure what's wrong here cause I'm new to Rails.
Any help will be appreciated.
Thanks
I'm not -entirely- sure, but I think you need to include "cached_model." Try adding
require 'cached_model' #(At the top)
Let me know if that worked.

Resources