jeudi 30 avril 2015

Stripe Connect OAuth/Devise integration with Rails: "No application matches the supplied client identifier"

I'm trying to integrate Stripe OAuth in a Rails application w/ Devise using this tutorial. I think I've followed it to a t, but I'm receiving this error when I go to Connect to Stripe on my app.

{"error":{"message":"No application matches the supplied client identifier"}}

I'm not sure how to check whether the client identifier I declare in my application.yml is even being passed in, or what value it's reading. Here's my setup so far:

config/application.yml (has my IDs from Stripe account - I edited them out here):

STRIPE_CONNECT_CLIENT_ID: "____________"
STRIPE_SECRET_KEY: "_____________"

config/initializers/devise.rb

Devise.setup do |config|

config.omniauth :stripe_connect,
      ENV['STRIPE_CONNECT_CLIENT_ID'],
      ENV['STRIPE_SECRET_KEY'],
      :scope => 'read_write',
      :stripe_landing => 'register'

*other config code*

end

config/routes.rb

Studiocracy::Application.routes.draw do
  devise_for :users, :controllers => { :omniauth_callbacks => "omniauth_callbacks", registrations: 'registrations' }
*other stuff*
end

controllers/omniauth_callbacks_controller.rb

class OmniauthCallbacksController < Devise::OmniauthCallbacksController

    def stripe_connect
        @user = current_user
        if @user.update_attributes({
            provider: request.env["omniauth.auth"].provider,
            uid: request.env["omniauth.auth"].uid,
            access_code: request.env["omniauth.auth"].credentials.token,
            publishable_key: request.env["omniauth.auth"].info.stripe_publishable_key
            })
      # anything else you need to do in response..
      sign_in_and_redirect @user, :event => :authentication
      set_flash_message(:notice, :success, :kind => "Stripe") if is_navigational_format?
  else
    session["devise.stripe_connect_data"] = request.env["omniauth.auth"]
    redirect_to new_user_registration_url
  end
end
end

app/views/devise/registrations/edit.html.erb

<%= link_to image_tag('stripe.png'), user_omniauth_authorize_path(:stripe_connect) %>

mercredi 29 avril 2015

Getting row value from DB by matching two column using Rails 3

I have a table like below structure.

table name users

id  Receipt_No   type   v_amount    v_date      c_date      v_name    v_status

7    150325006   SWD     60.00     2015-04-15  2015-04-28   Deepak    No

8    150325006   GOODS   1195.00   2015-04-15  2015-04-28   Deepak    No

9    150325006   BURNING  290.00   2015-04-15  2015-04-28  Deep       No

10   150325006   BURNING  290.00   2015-04-15   2015-04-15  Deep      No

I know only v_catagory and v_name column value.Suppose i have v_catagory="Deep" and v_name="BURNING" information.I need all row value whose v_name ="Deep" and v_catagory="BURNING" and finally display all required value in a table that means id no-9.10 should display in a table.Please help me.

Ruby on rails Crud for routes as namespaces

I am trying to create crud in rails. I think my routes in the namespace aren't working fine. When I try to create new record(country) it redirects me to index action when the request should go the create action on POST /admin/countries

Following is the code:

Controller:

class Admin::CountriesController < ApplicationController

    layout "admin"


  def index

    @countries = Country.all

  end

  def show
    @country = Country.find(params[:id])
  end

  def new
    @country = Country.new
  end

  def edit
    @country = Country.find(params[:id])
  end

  def create
    abort("Message goes here")
    @country = Country.new(country_params)
    if @country.save
        redirect_to @country
    else
        render 'new'
    end

  end

  def update
    @country = Country.find(params[:id])

    if @country.update(country_params)
        redirect_to @country
    else
        render 'edit'
    end

  end

  def destroy
        @country = Country.find(params[:id])
        @country.destroy

        redirect_to countries_path      
  end

  private
    def country_params
        params.require(:country).permit(:name, :status)
    end

end

Action-View (new)

<%= form_for [:admin, @country] do |f| %>
                  <div class="box-body">
                    <div class="form-group">
                      <%= f.label :name %>
                      <%= f.text_field :name, :class => 'form-control', :placeholder => 'Country name' %>
                    </div>
                    <div class="checkbox">
                      <label>
                        <%= f.check_box :status %> Is enabled?
                      </label>
                    </div>
                  </div><!-- /.box-body -->

                  <div class="box-footer">
                    <%= f.submit :class => "btn btn-primary" %>
                  </div>
                <% end %>

Routes

Rails.application.routes.draw do


  root "auth#login"

  get 'shop', :to => "auth#index"

  match ':controller(/:action(/:id))', :via => [:get,:post]
  match ':controller(/:action(/:id))', :via => [:get,:post], controller: /admin\/[^\/]+/

  namespace :admin do
   # root "auth#login"

    resources :countries
  end

end

Rails' link_to method: :delete not recognized on ipad. Sends GET request

There are many answers to similar questions that say to add

//= require jquery //= require jquery_ujs

to the application.js file. I already have these. My links work perfectly on desktop, however on the iPad, even though the link has the data-method="delete", the server still treats it as a GET request.

What is the fix to make this work on an ipad?

Here is my code:

<%= link_to "/things/#{thing.id}", :class => 'cool-thing', :method => :delete do %> <img src=awesome.png> <% end %>

spree footer never shows up

i can't display my footer. When I first installed, there wasn't any footer to begin with. Not sure if that's normal or not.

say i want this

Deface::Override.new(:virtual_path => 'spree/shared/_footer',
                     :name => 'footer',
                     :partial      => 'spree/shared/footer'
)

It doesn't show up. I go to app->views->layouts->application.html.erb and added <%= render 'spree/shared/footer' %> also tried <%= render partial: 'spree/shared/footer' %> nothing ever changes. BUT if i replace my header with my _footer file then I can see my footer. So this is a layout problem. Not sure why.

And I also tried

Deface::Override.new(:virtual_path => 'spree/shared/spree_application',
                     :name => 'footer',
                     :insert_after => 'div.container',
                     :partial      => 'spree/shared/footer'
)

nothing..

Why am I getting this TypeError? "no implicit conversion of Module into Integer"

I'm getting TypeError in CwIntegratorAccountsController#create. I'm calling a script (CwGetCompanyIntegrator.call) in the create method of the controller.

CwIntegratorAccountsController:

require 'apis/cw_get_company_integrator'

class CwIntegratorAccountsController < ApplicationController
  skip_before_filter :require_company, :only => [:create,:new]

  # GET /cw_integrator_accounts
  # GET /cw_integrator_accounts.json

  def create
    unless CwIntegratorAccount.count >= 1
      @cw_integrator_account = CwIntegratorAccount.new(params[:cw_integrator_account])

      respond_to do |format|
        if @cw_integrator_account.save

          # Run the CW Integrator
          CwGetCompanyIntegrator.call
          format.html { redirect_to root_url, notice: 'cw_integrator success' }
          #format.json { render json: @cw_integrator_account, status: :created, location: @cw_integrator_account }
        else
          format.html { render action: 'new' }
          format.json { render json: @cw_integrator_account.errors, status: :unprocessable_entity }
        end
      end
    end
  end
end

It looks like it's failing when it starts the https request to the ConnectWise Server at this line: response = http.start {|h| h.request(request)}

CwGetCompanyIntegrator script:

#!/usr/bin/env ruby
require 'net/https'
require 'uri'
require 'nokogiri'
require 'apis/cw_apis'

class CwGetCompanyIntegrator
  def self.call
    cw_integrator_account = CwIntegratorAccount.first
    cw_hostname = cw_integrator_account.cw_hostname
    company_api_url = "https://#{cw_hostname}/v4_6_release/apis/2.0/CompanyApi.asmx"
    uri = URI.parse(company_api_url)

    request = Net::HTTP::Post.new(uri.path)
    request.add_field('Content-Type', 'text/xml; charset=utf-8')
    request.add_field('SOAPAction', 'http://ift.tt/1GEDlOs')
    request.body = CwApis.get_company_xml_request
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    response = http.start {|h| h.request(request)}
    xml_doc = Nokogiri::XML(response.body).remove_namespaces!

    company_name = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/CompanyName').text
    company_street_addr = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/StreetLines/string')[0].text
    begin
      company_street_addr2 = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/StreetLines/string')[1].text
    end
    company_city = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/City').text
    company_state = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/State').text
    company_zip = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/Zip').text
    company_country = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/Country').text
    company_status = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/Status').text
    company_phone = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/PhoneNumber').text
    company_fax = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/FaxNumber').text
    company_www = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/WebSite').text

    CompanyInfosController.create!(cw_company_id: cw_integrator_account.cw_company_id, company_name: company_name,
                                   company_street_addr: company_street_addr, company_street_addr2: company_street_addr2,
                                   company_city: company_city, company_state: company_state, company_zip: company_zip,
                                   company_country:company_country, company_status: company_status, company_phone: company_phone,
                                   company_fax: company_fax, company_www: company_www)
  end
end

Full trace:

/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/http.rb:893:in `initialize'
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/http.rb:893:in `new'
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/http.rb:893:in `connect'
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/http.rb:862:in `do_start'
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/http.rb:851:in `start'
lib/apis/cw_get_company_integrator.rb:21:in `call'
app/controllers/cw_integrator_accounts_controller.rb:54:in `block in create'
actionpack (3.2.14) lib/action_controller/metal/mime_responds.rb:270:in `call'
actionpack (3.2.14) lib/action_controller/metal/mime_responds.rb:270:in `retrieve_collector_from_mimes'
actionpack (3.2.14) lib/action_controller/metal/mime_responds.rb:194:in `respond_to'
app/controllers/cw_integrator_accounts_controller.rb:50:in `create'
actionpack (3.2.14) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.2.14) lib/abstract_controller/base.rb:167:in `process_action'
actionpack (3.2.14) lib/action_controller/metal/rendering.rb:10:in `process_action'
actionpack (3.2.14) lib/abstract_controller/callbacks.rb:18:in `block in process_action'
activesupport (3.2.14) lib/active_support/callbacks.rb:447:in `_run__2237874046494148672__process_action__4163123032493016418__callbacks'
activesupport (3.2.14) lib/active_support/callbacks.rb:405:in `__run_callback'
activesupport (3.2.14) lib/active_support/callbacks.rb:385:in `_run_process_action_callbacks'
activesupport (3.2.14) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (3.2.14) lib/abstract_controller/callbacks.rb:17:in `process_action'
actionpack (3.2.14) lib/action_controller/metal/rescue.rb:29:in `process_action'
actionpack (3.2.14) lib/action_controller/metal/instrumentation.rb:30:in `block in process_action'
activesupport (3.2.14) lib/active_support/notifications.rb:123:in `block in instrument'
activesupport (3.2.14) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (3.2.14) lib/active_support/notifications.rb:123:in `instrument'
actionpack (3.2.14) lib/action_controller/metal/instrumentation.rb:29:in `process_action'
actionpack (3.2.14) lib/action_controller/metal/params_wrapper.rb:207:in `process_action'
activerecord (3.2.14) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
actionpack (3.2.14) lib/abstract_controller/base.rb:121:in `process'
actionpack (3.2.14) lib/abstract_controller/rendering.rb:45:in `process'
rack-mini-profiler (0.9.2) lib/mini_profiler/profiling_methods.rb:108:in `block in profile_method'
actionpack (3.2.14) lib/action_controller/metal.rb:203:in `dispatch'
actionpack (3.2.14) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
actionpack (3.2.14) lib/action_controller/metal.rb:246:in `block in action'
actionpack (3.2.14) lib/action_dispatch/routing/route_set.rb:73:in `call'
actionpack (3.2.14) lib/action_dispatch/routing/route_set.rb:73:in `dispatch'
actionpack (3.2.14) lib/action_dispatch/routing/route_set.rb:36:in `call'
journey (1.0.4) lib/journey/router.rb:68:in `block in call'
journey (1.0.4) lib/journey/router.rb:56:in `each'
journey (1.0.4) lib/journey/router.rb:56:in `call'
actionpack (3.2.14) lib/action_dispatch/routing/route_set.rb:608:in `call'
rack-webconsole-pry (0.1.9) lib/rack/webconsole/assets.rb:26:in `call'
rack-webconsole-pry (0.1.9) lib/rack/webconsole.rb:79:in `call'
actionpack (3.2.14) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
rack (1.4.5) lib/rack/etag.rb:23:in `call'
rack (1.4.5) lib/rack/conditionalget.rb:35:in `call'
actionpack (3.2.14) lib/action_dispatch/middleware/head.rb:14:in `call'
actionpack (3.2.14) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
actionpack (3.2.14) lib/action_dispatch/middleware/flash.rb:242:in `call'
rack (1.4.5) lib/rack/session/abstract/id.rb:210:in `context'
rack (1.4.5) lib/rack/session/abstract/id.rb:205:in `call'
actionpack (3.2.14) lib/action_dispatch/middleware/cookies.rb:341:in `call'
activerecord (3.2.14) lib/active_record/query_cache.rb:64:in `call'
activerecord (3.2.14) lib/active_record/connection_adapters/abstract/connection_pool.rb:479:in `call'
actionpack (3.2.14) lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
activesupport (3.2.14) lib/active_support/callbacks.rb:405:in `_run__2942276951910103516__call__2669772965393719582__callbacks'
activesupport (3.2.14) lib/active_support/callbacks.rb:405:in `__run_callback'
activesupport (3.2.14) lib/active_support/callbacks.rb:385:in `_run_call_callbacks'
activesupport (3.2.14) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (3.2.14) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
actionpack (3.2.14) lib/action_dispatch/middleware/reloader.rb:65:in `call'
actionpack (3.2.14) lib/action_dispatch/middleware/remote_ip.rb:31:in `call'
actionpack (3.2.14) lib/action_dispatch/middleware/debug_exceptions.rb:16:in `call'
actionpack (3.2.14) lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
railties (3.2.14) lib/rails/rack/logger.rb:32:in `call_app'
railties (3.2.14) lib/rails/rack/logger.rb:16:in `block in call'
activesupport (3.2.14) lib/active_support/tagged_logging.rb:22:in `tagged'
railties (3.2.14) lib/rails/rack/logger.rb:16:in `call'
actionpack (3.2.14) lib/action_dispatch/middleware/request_id.rb:22:in `call'
rack (1.4.5) lib/rack/methodoverride.rb:21:in `call'
rack (1.4.5) lib/rack/runtime.rb:17:in `call'
activesupport (3.2.14) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.4.5) lib/rack/lock.rb:15:in `call'
actionpack (3.2.14) lib/action_dispatch/middleware/static.rb:63:in `call'
rack-mini-profiler (0.9.2) lib/mini_profiler/profiler.rb:300:in `call'
railties (3.2.14) lib/rails/engine.rb:484:in `call'
railties (3.2.14) lib/rails/application.rb:231:in `call'
rack (1.4.5) lib/rack/content_length.rb:14:in `call'
railties (3.2.14) lib/rails/rack/log_tailer.rb:17:in `call'
rack (1.4.5) lib/rack/handler/webrick.rb:59:in `service'
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service'
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run'
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'

This works in a plain ruby script, is it an environment thing?

Working Ruby Scripts:

CompanyApis class:

require 'builder'
class CompanyApis
  def self.get_company
    cw_company_id = 21920
    integrator_company_id = 'COMPANY_ID'
    integrator_login_id = 'INTERGRATOR_LOGIN'
    integrator_password = 'INTERGRATOR_PW'

    xml = Builder::XmlMarkup.new(:indent=>2)
    xml.instruct!
    xml.tag!('soap:Envelope',
             :'xmlns:soap' => 'http://ift.tt/sVJIaE',
             :xmlns => 'http://connectwise.com'){
      xml.tag!('soap:Body'){
        xml.tag!('GetCompany'){
          xml.tag!('credentials'){
            xml.CompanyId(integrator_company_id)
            xml.IntegratorLoginId(integrator_login_id)
            xml.IntegratorPassword(integrator_password)
          }
          xml.id(cw_company_id)
        }
      }
    }
  end
end

CwIntegrator class:

require 'net/https'
require 'uri'
require 'nokogiri'
require './company_api'

class CwIntegrator
  def self.call
    cw_company_id = 21920
    cw_hostname = 'cw.i-techsupport.com'
    companyapi_url = "https://#{cw_hostname}/v4_6_release/apis/2.0/CompanyApi.asmx"
    uri = URI.parse(companyapi_url)

    # Use for proxying to Kali
    #proxy_addr = '172.16.1.149'
    #proxy_port = 8080

    request = Net::HTTP::Post.new(uri.path)
    request.add_field('Content-Type', 'text/xml; charset=utf-8')
    request.add_field('SOAPAction', 'http://ift.tt/1GEDlOs')
    request.body = CompanyApis.get_company
    http = Net::HTTP.new(uri.host, uri.port)

    # Use for proxying to Kali
    #http = Net::HTTP.new(uri.host, uri.port, proxy_addr, proxy_port)

    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    response = http.start {|h| h.request(request)}
    company_info = []
    xml_doc = Nokogiri::XML(response.body).remove_namespaces!
    company_name = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/CompanyName').text
    company_street_addr = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/StreetLines/string')[0].text
    begin
      company_street_addr2 = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/StreetLines/string')[1].text
    end
    company_city = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/City').text
    company_state = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/State').text
    company_zip = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/Zip').text
    company_country = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/Country').text
    company_status = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/Status').text
    company_phone = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/PhoneNumber').text
    company_fax = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/FaxNumber').text
    company_www = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/WebSite').text

    company_info += [company_name: company_name, cw_company_id: cw_company_id, company_name: company_name,
                     company_street_addr: company_street_addr, company_street_addr2: company_street_addr2,
                     company_city: company_city, company_state: company_state, company_zip: company_zip,
                     company_country:company_country,company_status: company_status, company_phone: company_phone,
                     company_fax: company_fax, company_www: company_www]

    puts(company_info)
  end
end

CwIntegrator.call

Faye chat application failing on web server (bluehost)

This is more of a network question , I believe. Not sure what the issue is. I have a chat application which uses faye and it runs fine on my system(rails app) with localhost:3000 having faye mounted on it.I recently deployed this rails app onto bluehost server and when I try to use the faye client on browser ,its giving me this error:

WebSocket connection to 'ws://chat.xyz.com/faye' failed: Error during WebSocket handshake: Unexpected response code: 500

GET http://...chat.xyz.com/faye?message=%5B%7B%22channel%22%3A%22%2Fmet…ing%22%5D%2C%22id%22%3A%221%22%2C%22ext%22%3A%7B%7D%7D%5D&jsonp=jsonp3 GET http://...chat.xyz.com/faye?message=%5B%7B%22channel%22%3A%22%2Fmet…ing%22%5D%2C%22id%22%3A%221%22%2C%22ext%22%3A%7B%7D%7D%5D&jsonp=jsonp4

GET http://...chat.xyz.com/faye?message=%5B%7B%22channel%22%3A%22%2Fmet…ing%22%5D%2C%22id%22%3A%221%22%2C%22ext%22%3A%7B%7D%7D%5D&jsonp=jsonp5

GET http://...chat.xyz.com/faye?message=%5B%7B%22channel%22%3A%22%2Fmet…ing%22%5D%2C%22id%22%3A%221%22%2C%22ext%22%3A%7B%7D%7D%5D&jsonp=jsonp6

GET http://...chat.xyz.com/faye?message=%5B%7B%22channel%22%3A%22%2Fmet…ing%22%5D%2C%22id%22%3A%221%22%2C%22ext%22%3A%7B%7D%7D%5D&jsonp=jsonp7

GET http://...chat.xyz.com/faye?message=%5B%7B%22channel%22%3A%22%2Fmet…ing%22%5D%2C%22id%22%3A%221%22%2C%22ext%22%3A%7B%7D%7D%5D&jsonp=jsonp8

GET http://...chat.xyz.com/faye?message=%5B%7B%22channel%22%3A%22%2Fmet…ing%22%5D%2C%22id%22%3A%221%22%2C%22ext%22%3A%7B%7D%7D%5D&jsonp=jsonp9

GET http://...chat.xyz.com/faye?message=%5B%7B%22channel%22%3A%22%2Fmet…ng%22%5D%2C%22id%22%3A%221%22%2C%22ext%22%3A%7B%7D%7D%5D&jsonp=jsonp10

And the failed handshakes\requests keep on getting repeated. Seeing the same on server logs also(except the 500 message obviously). The logs dont give any error apart from these repeats

Is it because of proxy\firewall issue. I recently came across an article : http://ift.tt/l1TrF1

I am not sure whether its related to blocking of requests by proxy servers.

Tried switching to secure protcol. https. Didn't help. I use a simple client like this:

var client = new Faye.Client('http://ift.tt/1EQvOyG');

Any help would be great.

Can we override operators in Ruby?

in a case...such as

(10 + 20) * 10
=> 300

the expression fragment enclosed in parentheses is evaluated before the higher precedence multiplication.So does it applies to other operators as well.Can i override other operators such as << !...etc

Why are my scripts from lib/assets directory in a Rails application not executing, or erring out?

I'm trying to use ConnectWise API's in my Rails 3 application. I've built and tested an API using plain ruby and it's successful. Now I'm trying to add this script into lib/assets in my Rails app to run but It seems to be either not executing the script, or executing and failing without giving me any error output.

Here are the successful Ruby scripts:

CompanyApis Class:

require 'builder'
class CompanyApis
  def self.get_company
    cw_company_id = 21920
    integrator_company_id = 'COMPANY_ID'
    integrator_login_id = 'INTERGRATOR_LOGIN'
    integrator_password = 'INTEGRATOR PW'

    xml = Builder::XmlMarkup.new(:indent=>2)
    xml.instruct!
    xml.tag!('soap:Envelope',
             :'xmlns:soap' => 'http://ift.tt/sVJIaE',
             :xmlns => 'http://connectwise.com'){
      xml.tag!('soap:Body'){
        xml.tag!('GetCompany'){
          xml.tag!('credentials'){
            xml.CompanyId(integrator_company_id)
            xml.IntegratorLoginId(integrator_login_id)
            xml.IntegratorPassword(integrator_password)
          }
          xml.id(cw_company_id)
        }
      }
    }
  end
end

CwIntegrator Class:

require 'net/https'
require 'uri'
require 'nokogiri'
require './company_api'

class CwIntegrator
  cw_company_id = 21920
  cw_hostname = 'cw.host.com'
  companyapi_url = "https://#{cw_hostname}/v4_6_release/apis/2.0/CompanyApi.asmx"
  uri = URI.parse(companyapi_url)

  # Use for proxying to Kali
  #proxy_addr = '172.16.1.149'
  #proxy_port = 8080

  request = Net::HTTP::Post.new(uri.path)
  request.add_field('Content-Type', 'text/xml; charset=utf-8')
  request.add_field('SOAPAction', 'http://ift.tt/1GEDlOs')
  request.body = CompanyApis.get_company
  http = Net::HTTP.new(uri.host, uri.port)

  # Use for proxying to Kali
  #http = Net::HTTP.new(uri.host, uri.port, proxy_addr, proxy_port)

  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  response = http.start {|h| h.request(request)}
  company_info = []
  xml_doc = Nokogiri::XML(response.body).remove_namespaces!
  company_name = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/CompanyName').text
  company_street_addr = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/StreetLines/string')[0].text
  begin
    company_street_addr2 = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/StreetLines/string')[1].text
  end
  company_city = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/City').text
  company_state = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/State').text
  company_zip = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/Zip').text
  company_country = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/Country').text
  company_status = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/Status').text
  company_phone = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/PhoneNumber').text
  company_fax = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/FaxNumber').text
  company_www = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/WebSite').text

  company_info += [company_name: company_name, cw_company_id: cw_company_id, company_name: company_name,
                   company_street_addr: company_street_addr, company_street_addr2: company_street_addr2,
                   company_city: company_city, company_state: company_state, company_zip: company_zip,
                   company_country:company_country,company_status: company_status, company_phone: company_phone,
                   company_fax: company_fax, company_www: company_www]

  puts(company_info)
end

Running this script has this output:

ruby cw_integrator.rb {:company_name=>"Orlando Fake Co, LLC.", :cw_company_id=>21920, :company_street_addr=>"STREET ADDR.", :company_street_addr2=>"Suite 400", :company_city=>"Orlando", :company_state=>"FL", :company_zip=>"32839", :company_country=>"United States", :company_status=>"Active Gold TTS", :company_phone=>"5558765309", :company_fax=>"", :company_www=>"www.myweb.com"}

So to add this to the Rails app I've added two .rb files to lib/assets, cw_apis.rb and cw_get_company_integrator.rb. Here are their contents:

CwApis class:

#!/usr/bin/env ruby
require 'builder'
class CwApis
  def self.get_company_xml_request
    cw_integrator_account = CwIntegratorAccount.first
    integrator_company_id = cw_integrator_account.integrator_company_id
    integrator_login_id = cw_integrator_account.integrator_login_id
    integrator_password = cw_integrator_account.integrator_password

    xml = Builder::XmlMarkup.new(:indent=>2)
    xml.instruct!
    xml.tag!('soap:Envelope',
             :'xmlns:soap' => 'http://ift.tt/sVJIaE',
             :xmlns => 'http://connectwise.com'){
      xml.tag!('soap:Body'){
        xml.tag!('GetCompany'){
          xml.tag!('credentials'){
            xml.CompanyId(integrator_company_id)
            xml.IntegratorLoginId(integrator_login_id)
            xml.IntegratorPassword(integrator_password)
          }
          xml.id(cw_integrator_account.cw_company_id)
        }
      }
    }
  end
end

And CwGetCompanyIntegrator Class:

#!/usr/bin/env ruby
require 'net/https'
require 'uri'
require 'nokogiri'
require 'assets/cw_apis'

class CwGetCompanyIntegrator
  cw_integrator_account = CwIntegratorAccount.first
  cw_hostname = cw_integrator_account.cw_hostname
  company_api_url = "https://#{cw_hostname}/v4_6_release/apis/2.0/CompanyApi.asmx"
  uri = URI.parse(company_api_url)

  request = Net::HTTP::Post.new(uri.path)
  request.add_field('Content-Type', 'text/xml; charset=utf-8')
  request.add_field('SOAPAction', 'http://ift.tt/1GEDlOs')
  request.body = CwApis.get_company_xml_request
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL
  response = http.start {|h| h.request(request)}
  xml_doc = Nokogiri::XML(response.body).remove_namespaces!

  company_name = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/CompanyName').text
  company_street_addr = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/StreetLines/string')[0].text
  begin
    company_street_addr2 = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/StreetLines/string')[1].text
  end
  company_city = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/City').text
  company_state = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/State').text
  company_zip = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/Zip').text
  company_country = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/DefaultAddress/Country').text
  company_status = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/Status').text
  company_phone = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/PhoneNumber').text
  company_fax = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/FaxNumber').text
  company_www = xml_doc.xpath('//Envelope/Body/GetCompanyResponse/GetCompanyResult/WebSite').text

  CompanyInfosController.create!(cw_company_id: cw_integrator_account.cw_company_id, company_name: company_name,
                                 company_street_addr: company_street_addr, company_street_addr2: company_street_addr2,
                                 company_city: company_city, company_state: company_state, company_zip: company_zip,
                                 company_country:company_country, company_status: company_status, company_phone: company_phone,
                                 company_fax: company_fax, company_www: company_www)
end

I'm trying to execute the CwGetCompanyIntegrator class in my CwIntegratorAccountsController.

Here is the code inside the create action from the CwIntegratorAccountsController:

require 'assets/cw_get_company_integrator'

class CwIntegratorAccountsController < ApplicationController
  skip_before_filter :require_company, :only => [:create,:new]

  # GET /cw_integrator_accounts
  # GET /cw_integrator_accounts.json

  def create
    unless CwIntegratorAccount.count >= 1
      @cw_integrator_account = CwIntegratorAccount.new(params[:cw_integrator_account])

      respond_to do |format|
        if @cw_integrator_account.save

          # Run the CW Integrator
          CwGetCompanyIntegrator
          format.html { redirect_to root_url, notice: 'cw_integrator success' }
          #format.json { render json: @cw_integrator_account, status: :created, location: @cw_integrator_account }
        else
          format.html { render action: 'new' }
          format.json { render json: @cw_integrator_account.errors, status: :unprocessable_entity }
        end
      end
    end
  end
end

What is the proper way to make this class execute?

Set nested params values before_validation in rails

I have a model Request and nested model to it filled_cartridges.

has_many :filled_cartridges, inverse_of: :request, dependent: :destroy
accepts_nested_attributes_for :filled_cartridges, reject_if: proc { |attributes| attributes['title'].blank? },allow_destroy: true

And my strong params:

def request_params
 params.require(:request).permit(:name,:type,
  :filled_cartridges_attributes => [:client_id,:cartridge_name,:cartridge_id,
:request_id,:_destroy,:id],

end

Using this method I believe my nested model is autosave when parent (request) model is saved. And there may be many filled_cartridges.

What I want to do is to set client_id and cartridge_id before_validation happens, if I won't they they will fail in not null constraint. I believe before_validation calls some method before every object validation. So i believe that before_validation will call my method before validation for all nested objects.

This is how i am trying to use before_validation:

before_validation :set_attributes, only: [:create]
....

protected
  def set_attributes
        @client = Client.where("name = ?", self.name).take # this is  a problematic
        @cartridge = Cartridge.where('cartridge_name=?', self[:filled_cartridges_attributes][:cartridge_name].take # this is too
        self.client_id = @client.id
        self.cartrdige_id = @cartridge.id
end

In the first two lines of set_attributes I want to first find my client and cartridge objects. And for that I want to use values from strong_params. How can I do that?

How to implement price table in ruby on rails?

I am making one rails application which allows companies to list their products on my website which was built with rails. Now I want to charge some money both monthly or yearly for listing their products on my site which accepts credit card and PayPal.

How can I implement this using ruby on rails. similar to this. Link

Rip pdf document into pages ruby

I am trying to rip a pdf file into pages in ruby language.
I have came across several libraries like prawn,pdf-reader,doc-split etc Is there any library which can extract pages form a pdf document and reconstruct several pdfs one document for one page or just extract the html pages which looks similar to pdf

chartkick loading issue with Ajax

I added a graph partial and called this method of Chartkick to load the graphs, it works fine with HTML request. When i call it with Ajax. i always see LOADING error. any idea what could be the reason of this ?

   = pie_chart Goal.group(:name).count

I'm using Rails 4.1.9 and ruby ruby 2.1.5

Model with namespace - wrong table name (without namespace)

I found a problem in one of legacy applications (outdated rails-3.0.20). This application has lots of components and nested models. Problem existed only on one of production servers (same environments like other productions and mine dev).

There was model with name space which looks like

module Great
  class Item
  end
end

Table name was named great_items.

When i debug/open it on server with fault i've found that calculated table name was items istead of great_items.

$ Great::Item.all
#=> ActiveRecord::StatementInvalid: No attribute named `name` exists for table `items`

So i thought mby there is simmilar class with same namespace, I've checked it and it wasn't. My 2nd thought was to set table name explicit i tried

self.table_name = 'great_items'
# &
set_table_name 'great_items'

After this changes i run rails c and table name was setted fine:

$ Great::Items.table_name
#=> 'great_items'

But when i tried to obtain some items there was a freak error, which i could not understand till now!

$ Great::Items.all
#=> ActiveRecord::StatementInvalid: Mysql2::Error: Table 'db.items' doesn't exist: SELECT `great_items`.* FROM `items` WHERE `great_items`.`some_default_scope` = 0

As you can see in above example table has correct name for select values and in where statement, but in from value is incorrect.

I was curious so I've checked ActiveRecord::Base mysql adapter and there was some kind of catching table name so i tried to reset_table_name. Reset helped to setup expected name('great_items') but above errors didn't missed.

Problem dissapeared when i turn of class catching in production enviroment - but it wasn't solution.

Finally I kinda 'solved' this using reset_column_information after set_table_name, but i think it isn't good solution either.

My question is do you know what really could cause this issue and how to solve it without reloading class cache?

mardi 28 avril 2015

RoR - Devise Mailer - gmail refusing to send message

Currently I am working on Cloud9 and trying to create a rails app where the Devise mailer can send the reset password function and other built in mailing features.

What I think is happening, is that gmail is refusing to send the message because of the account. I even went on gmail and found the cloud9 server that was sending the request and checked "This is me" for the IP address... but it still isn't working

What I have tried:

  1. http://ift.tt/1Dyy1Yj this link allows your account to receive message requests from "less secure" applications.
  2. Changing port number - then we get a time out error rather than our current one.
  3. tried yahoo account - similar error

Relevant files:

log/development.log:

Devise::Mailer#reset_password_instructions: processed outbound mail in 646.5ms

Sent mail to nick.dueber@gmail.com (60.6ms)
Date: Tue, 28 Apr 2015 20:32:39 +0000
From: newstab123@gmail.com
Reply-To: newstab123@gmail.com
To: nick.dueber@gmail.com
Message-ID: <553fee678a275_4542521a93097522@ryan_yu-cs169-newstab-1298669.mail>
Subject: Reset password instructions
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

<p>Hello nick.dueber@gmail.com!</p>

<p>Someone has requested a link to change your password. You can do this through the link below.</p>

<p><a href="http://localhost:3000/profile/users/password/edit?    reset_password_token=VhJFo7yaAsL3tCg2U4Tm">Change my password</a></p>

<p>If you didn't request this, please ignore this email.</p>
<p>Your password won't change until you access the link above and create a new one.</p>

Completed 500 Internal Server Error in 1242ms

Net::SMTPAuthenticationError (530-5.5.1 Authentication Required. Learn more at
):
  /usr/local/rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/net/smtp.rb:957:in `check_response'
  /usr/local/rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/net/smtp.rb:926:in `getok'
  /usr/local/rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/net/smtp.rb:841:in `mailfrom'
  /usr/local/rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/net/smtp.rb:662:in `send_message'
  mail (2.6.3) lib/mail/network/delivery_methods/smtp.rb:113:in `block in deliver!'
  /usr/local/rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/net/smtp.rb:521:in `start'
  mail (2.6.3) lib/mail/network/delivery_methods/smtp.rb:112:in `deliver!'
  mail (2.6.3) lib/mail/message.rb:2141:in `do_delivery'
  mail (2.6.3) lib/mail/message.rb:236:in `block in deliver'
  actionmailer (4.1.6) lib/action_mailer/base.rb:527:in `block in     deliver_mail'
   activesupport (4.1.6) lib/active_support/notifications.rb:159:in `block in instrument'
  activesupport (4.1.6) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.1.6) lib/active_support/notifications.rb:159:in `instrument'
  actionmailer (4.1.6) lib/action_mailer/base.rb:525:in `deliver_mail'
  mail (2.6.3) lib/mail/message.rb:236:in `deliver'
  devise (3.4.1) lib/devise/models/authenticatable.rb:178:in     `send_devise_notification'
  devise (3.4.1) lib/devise/models/recoverable.rb:99:in `send_reset_password_instructions_notification'
  devise (3.4.1) lib/devise/models/recoverable.rb:49:in `send_reset_password_instructions'
  devise (3.4.1) lib/devise/models/recoverable.rb:116:in `send_reset_password_instructions'
   devise (3.4.1) app/controllers/devise/passwords_controller.rb:13:in `create'
  actionpack (4.1.6) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
  actionpack (4.1.6) lib/abstract_controller/base.rb:189:in `process_action'
  actionpack (4.1.6) lib/action_controller/metal/rendering.rb:10:in `process_action'
  actionpack (4.1.6) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
  activesupport (4.1.6) lib/active_support/callbacks.rb:113:in `call'
  activesupport (4.1.6) lib/active_support/callbacks.rb:113:in `call'
  activesupport (4.1.6) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
  activesupport (4.1.6) lib/active_support/callbacks.rb:149:in `call'
  activesupport (4.1.6) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
  activesupport (4.1.6) lib/active_support/callbacks.rb:229:in `call'
  activesupport (4.1.6) lib/active_support/callbacks.rb:229:in `block in halting'
  activesupport (4.1.6) lib/active_support/callbacks.rb:229:in `call'
  activesupport (4.1.6) lib/active_support/callbacks.rb:229:in `block in halting'
  activesupport (4.1.6) lib/active_support/callbacks.rb:166:in `call'
  activesupport (4.1.6) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.6) lib/active_support/callbacks.rb:166:in `call'
  activesupport (4.1.6) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.6) lib/active_support/callbacks.rb:166:in `call'
  activesupport (4.1.6) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.6) lib/active_support/callbacks.rb:166:in `call'
  activesupport (4.1.6) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.6) lib/active_support/callbacks.rb:166:in `call'
  activesupport (4.1.6) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.6) lib/active_support/callbacks.rb:86:in `call'
  activesupport (4.1.6) lib/active_support/callbacks.rb:86:in `run_callbacks'
  actionpack (4.1.6) lib/abstract_controller/callbacks.rb:19:in `process_action'
  actionpack (4.1.6) lib/action_controller/metal/rescue.rb:29:in `process_action'
  actionpack (4.1.6) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
  activesupport (4.1.6) lib/active_support/notifications.rb:159:in `block in instrument'
  activesupport (4.1.6) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.1.6) lib/active_support/notifications.rb:159:in `instrument'
  actionpack (4.1.6) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
  actionpack (4.1.6) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
  activerecord (4.1.6) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
  actionpack (4.1.6) lib/abstract_controller/base.rb:136:in `process'
  actionview (4.1.6) lib/action_view/rendering.rb:30:in `process'
  actionpack (4.1.6) lib/action_controller/metal.rb:196:in `dispatch'
  actionpack (4.1.6) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
  actionpack (4.1.6) lib/action_controller/metal.rb:232:in `block in action'
  actionpack (4.1.6) lib/action_dispatch/routing/route_set.rb:82:in `call'
  actionpack (4.1.6) lib/action_dispatch/routing/route_set.rb:82:in `dispatch'
  actionpack (4.1.6) lib/action_dispatch/routing/route_set.rb:50:in `call'
  actionpack (4.1.6) lib/action_dispatch/routing/mapper.rb:45:in `call'
    actionpack (4.1.6) lib/action_dispatch/journey/router.rb:73:in `block in call'
    actionpack (4.1.6) lib/action_dispatch/journey/router.rb:59:in `each'
    actionpack (4.1.6) lib/action_dispatch/journey/router.rb:59:in `call'
    actionpack (4.1.6) lib/action_dispatch/routing/route_set.rb:678:in `call'
    omniauth (1.2.2) lib/omniauth/strategy.rb:186:in `call!'
    omniauth (1.2.2) lib/omniauth/strategy.rb:164:in `call'
    warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
    warden (1.2.3) lib/warden/manager.rb:34:in `catch'
    warden (1.2.3) lib/warden/manager.rb:34:in `call'
    rack (1.5.2) lib/rack/etag.rb:23:in `call'
    rack (1.5.2) lib/rack/conditionalget.rb:35:in `call'
    rack (1.5.2) lib/rack/head.rb:11:in `call'
    actionpack (4.1.6) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
    actionpack (4.1.6) lib/action_dispatch/middleware/flash.rb:254:in `call'
    rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context'
    rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'
    actionpack (4.1.6) lib/action_dispatch/middleware/cookies.rb:560:in `call'
    activerecord (4.1.6) lib/active_record/query_cache.rb:36:in `call'
    activerecord (4.1.6)       lib/active_record/connection_adapters/abstract/connection_pool.rb:621:in `call'
   activerecord (4.1.6) lib/active_record/migration.rb:380:in `call'
    actionpack (4.1.6) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
    activesupport (4.1.6) lib/active_support/callbacks.rb:82:in `run_callbacks'
    actionpack (4.1.6) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
    actionpack (4.1.6) lib/action_dispatch/middleware/reloader.rb:73:in `call'
    actionpack (4.1.6) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
    actionpack (4.1.6) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
    actionpack (4.1.6) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
    railties (4.1.6) lib/rails/rack/logger.rb:38:in `call_app'
    railties (4.1.6) lib/rails/rack/logger.rb:20:in `block in call'
    activesupport (4.1.6) lib/active_support/tagged_logging.rb:68:in `block in tagged'
    activesupport (4.1.6) lib/active_support/tagged_logging.rb:26:in `tagged'
    activesupport (4.1.6) lib/active_support/tagged_logging.rb:68:in `tagged'
    railties (4.1.6) lib/rails/rack/logger.rb:20:in `call'
    actionpack (4.1.6) lib/action_dispatch/middleware/request_id.rb:21:in `call'
    rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
    rack (1.5.2) lib/rack/runtime.rb:17:in `call'
    activesupport (4.1.6)       lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'
    rack (1.5.2) lib/rack/lock.rb:17:in `call'
    actionpack (4.1.6) lib/action_dispatch/middleware/static.rb:64:in `call'
    rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
    railties (4.1.6) lib/rails/engine.rb:514:in `call'
    railties (4.1.6) lib/rails/application.rb:144:in `call'
    rack (1.5.2) lib/rack/lock.rb:17:in `call'
    rack (1.5.2) lib/rack/content_length.rb:14:in `call'
    rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
    /usr/local/rvm/rubies/ruby-      2.1.5/lib/ruby/2.1.0/webrick/httpserver.rb:138:in `service'
    /usr/local/rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/webrick/httpserver.rb:94:in `run'
    /usr/local/rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/webrick/server.rb:295:in `block in start_thread'

config/environments/development.rb:

# Show full error reports and disable caching.
config.consider_all_requests_local       = true
config.action_controller.perform_caching = false

# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true

config.action_mailer.perform_deliveries = true

config.action_mailer.default_url_options = { :host => 'localhost:3000' }

config.action_mailer.delivery_method = :smtp


config.action_mailer.smtp_settings = {
   address: "smtp.gmail.com",
   port: 587,
   domain: ENV["gmail.com"],
   authentication: "plain",
   enable_starttls_auto: true,
   user_name: ENV["coolEmail@gmail.com"],
   password: ENV["coolPassword"],
   openssl_verify_mode: 'none',
}

rails 3 parsing date using strftime

Having a problem parsing dates taken in from scraping a website using nokogiri. I scrape the datetime using

@date = h4.at('time[itemprop="startDate"]')[:datetime]

This gives me 2015-04-28 19:30:00 UTC, which is inserted into my date column, of type datetime.

Using strptime I am trying to parse the date into a dd/mm format, and enter it into my rails table.

Date.strptime(@date, "%Y-%m-%d %H:%M:%S %Z").strftime("%m/%d/%Y")

@event=Event.new
@event.date= @date

Any help would be very much appreciated. Thanks in advance

Uploading error with nginx and thin server in Rails production

I have deployed my app here http://jobmre.com/ with nginx and thin server.

When i tried to upload big files mp4 files like size of 100MB. I have this error below check screenshot.

enter image description here

Any help to resolve this issues.I am using paperclip for uploading.

Thanks

Getting redirected to session_expired using Grinder script on Rails 3 for load testing website- API testing

I recently created an API for a website. Now I was doing load testing using grinder script in which the user logs in, goes to home page and then the blogs page, submits the blog and then the api service is called and it gives a response which is then stored in our DB. It works fine through browser but when the same thing is done through recorded Grinder script I get Filter chain halted as :login_required rendered or redirected in my rails app log. I have tried commenting protect_from_forgery have also given skip_before_filter :verify_authenticity_token in the controller but still for every request made it keeps going to session_expired. Please help.

I am using AJAX for posting blog and getting response from the API. And I cannot remove the login mechanism for testing purpose load testing has to be done with login functionality.

Rails 3 with omniauth-google-oauth2 fails behind a proxy

Works find when accessed directly and fails with

Not found. Authentication passthru.

when behind a reverse proxy

Trying to create a share link that will show a secure url of the same page to be share with others in ruby on rails

i would like to create a link on button just like google docs or dropbox share url link button to show the secure url of the same page in a pop up menu using ruby-on-rails. So that we can share that url to anybody for the access of that page.The person who will use the link wouldn't have to authenticate his/herself.

Ruby gems helper method (permitted_to?) in rails console

I am using declarative_authorization. I want to use permitted_to? method in rails console. How can I use it?

uninitialized constant file in subfolder

My test folder is structured like this:

  test
    models
      restaurant
        helpers
           employee.rb
        points_test.rb

So my PointsTest looks like this:

require 'models/restaurant/helpers/employee.rb' 

   class Restaurant::PointsTest < ActiveSupport::TestCase
     ....
     employee1 = Restaurant::Employee.create

And the file Employee like this:

class Restaurant::Employee
   def self.create
     .....

Everything works like this

---------------------------------------------

Now i tried to change class Restaurant::Employee to class Restaurant::Helpers::Employee

and in PointsTest i changed to employee1 = Restaurant::Helpers::Employee.create

And I get this error:

uninitialized constant Restaurant::Helpers (NameError)

What do I wrong? I mean Helpers is in the subfolder helpers! Thank you

lundi 27 avril 2015

Rails Exception Notification without middleware

I have an Rails 4 application that is entirely comprised of rails runners over cron generated from the whenever gem.

I'd like to be notified if there are any exceptions that occur during the run. The exception_notification gem only runs as rack middleware (web requests only), so it doesn't handle rails runners.

Any ideas? I'm looking to get notified over email or on slack.

gem install rails -y doesn't work with ruby 2.1.6 in Windows 8

Hi experts about Ruby.

I'm pretty new on this fantastic and funny language, but I immediately meet an error with my command prompt.

I typed, because Win8, gem install rails -y but system said: "gem" is not a batch command or file and bla bla bla..

Why this?

How can i resolve?

Pass parameters to method of validation customized

I am a newbie in Rails. I am trying pass a value to a method of validation customized, but I get the following error

class Person < ActiveRecord::Base
  attr_accessible :first_name, :last_name, :age

  validate :something, 56

  def something(value=67)
   errors.add(:first_name, "cannot contain the characters !@#%*()_-+= # #{value}") 
  end
end

error

1.9.3-p194 :002 > p=Person.new
 => #<Person id: nil, first_name: nil, last_name: nil, age: nil, is_admin: nil, created_at: nil, updated_at: nil> 
1.9.3-p194 :003 > p.save
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
NoMethodError: undefined method `validate' for 56:Fixnum
    from /home/fernando/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:310:in `_callback_before_13'

How to fetch attribute value from database and apply to form

I am trying to get the background-color for forms from the user and storing the value in user_preference table and applying those back-ground color by fetching data from table into the same form.

My forms look like this:

<%= form_for @user_preference do |u|%>
 <p>
    <%= u.label :title %><br>
    <%= u.text_field :title %>
  </p>

  <p>
    <%= u.label :description %><br>
    <%= u.text_field :description %>
  </p>

  <p> <%= u.label :back_ground_color %><br>
    <%= u.select :bgcolor, options_for_select(UserPreference.bgcolor_options) %>
  </p>

  <p>
    <%= u.label :font %><br>
    <%= u.select :font, options_for_select(UserPreference.font_options) %>

  </p>

 <br >
  <p>
    <%= u.submit %>
  </p>
  <div style="<%= 'background-color:#{@user_preference.bgcolor};' %>"</style></div>
  <hr >
<% end %>

I am rendering this form again after saving the value in database, is this the way to do ?

here is my controller:

class UserPreferencesController < ApplicationController
    def new
        @user_preference = UserPreference.new
    end

    def create
        @user_preference = UserPreference.new(user_pref_params)
        @user_preference.user = current_user
        @user_preference.save if user_signed_in?
        render 'user_preferences/new'
    end

Is it the correct way of doing... let me know where I am doing mistake, any help will be appreciated.

join 3 tables though RAils 3 models ruby 1.8.7

i have 3 tables, gifts, users and orders. i need to store the id from those 3 in a 4th tables to stablish a relationship.

the gift can be used only once per user AND per order, but a gift can be used by many different users.

i'm kinda lost in that becouse this is too much info for me yet.

thank you for the attention :)

passing parameters between views and controllers ruby 1.8.7

i have this form nested in view 'A'

<div>
<%if current_user%> 
    <%=form_for(ModelB.new) do |f|%>
      <%if (params[:param_to_check].present?)%>
        <%f.hidden_field "param1",:value=> @modelA.id%>
        <%f.hidden_field "param2",:value=> current_user.id%>
      <%end%>
    render button
    <%end%>
<%else%>
    render other butotn
<%end%>

</div>

and this 'find' in Bs_controller:

@modelA=ModelA.find_by_id(params[:param1])
  :option_from_specific_gem=> -(@modelA.wanted_value).abs

when i look to the params passed to the Bs_controller i see:

Parameters: {"authenticity_token"=>"some_hash=", "utf8"=>"✓", "y"=>"42", "x"=>"144"}

and i need to pass the hidden_field's valies to Bs_controller.

thx for the atention :)

here is the gist: http://ift.tt/1bwLNEw

How to handle concurrent requests that delete and create the same rows?

I have a table that looks like the following:

game_stats table:

id | game_id | player_id | stats | (many other cols...)
----------------------
1  | 'game_abc' | 8 | 'R R A B S' | ...
2  | 'game_abc' | 9 | 'S B A S' | ...

A user uploads data for a given game in bulk, submitting both players' data at once. For example:

"game": {
  id: 'game_abc',
  player_stats: {
    8: {
      stats: 'R R A B S'
    },
    9: {
      stats: 'S B A S'
    }
  }
}

Submitting this to my server should result in the first table.

Instead of updating the existing rows when the same data is submitted again (with revisions, for example) what I do in my controller is first delete all existing rows in the game_stats table that have the given game_id:

class GameStatController
    def update
      GameStat.where("game_id = ?", game_id).destroy_all
      params[:game][:player_stats].each do |stats|
        game_stat.save
      end
    end
end

This works fine with a single threaded or single process server. The problem is that I'm running Unicorn, which is a multi-process server. If two requests come in at the same time, I get a race condition:

Request 1: GameStat.where(...).destroy_all
Request 2: GameStat.where(...).destroy_all
Request 1: Save new game_stats
Request 2: Save new game_stats

Result: Multiple game_stat rows with the same data.

I believe somehow locking the rows or table is the way to go to prevent multiple updates at the same time - but I can't figure out how to do it. Combining with a transaction seems the right thing to do, but I don't really understand why.

EDIT

To clarify why I can't figure out how to use locking: I can't lock a single row at a time, since the row is simply deleted and not modified.

Nested routes error in Rails

In my rails application I have this routes

resources :jobs do
  resources :job_applications, :path =>  'applications' do
    member do 
      put :change_stage
    end
  end
end

And I have a method called change_stage in my job_application controller Actually I'm trying to change one params of the job_application in an modal so for this I have this in the modal body

<%=form_for :job_application, :url => change_stage_job_job_application.(params[:application_status]), :html => {:method => :post, :class => 'form-horizontal' } do |f| %>

<%= label :status, 'reject' %>
<%= f.radio_button :application_status, 'reject' %><br>
<%= label :status, 'interview' %>
<%= f.radio_button :application_statuss, 'interview' %><br>
<%= label :status, 'hired' %>
<%= f.radio_button :application_status, 'hired' %>

<% end %>

but I'm getting this error

undefined local variable or method `change_stage_job_application' for #<#<Class:0xb463b49c>:0xb463ac04>

What is wrong in my form

Change only one field of model in Rails

In my Rails app I have a model called application ins this model I have a field called status, this is my model

class Application < ActiveRecord::Base
    belongs_to :job
    belongs_to :user

    scope :new, where(:status => 'New')
    scope :reviewed, where(:status => 'Profile Reviewed')
    scope :offered, where(:status => 'Offer Given')
    scope :accepted, where(:status => 'Offer Accepted')
    scope :hired, where(:status => 'Hired')
    scope :declined, where(:status => 'Decline')

I'm wondering if it is possible to change only the status in an modal (all status with checkbox) in the application show page if so what is the best ways to do it, or the status must be a separated model

Rails security: allowing slash as user input

I have a Rails 3.2.21 application. One of my users has an address with a slash in it (think Main Street 321 1/2). Currently, we filter out slashes, which makes this user's address invalid. How can I allow this address through without either disabling the validation for this particular address or allowing slashes globally (a huge security risk)? Is there a way I can encode the slash, put it into the database and encode it back to a slash upon retrieval?

Thank you!

Rails Memory HIGH Memory Usage

I have installed oink . it shows below output. There is whosin action in attendance controller takes around 471 MB RAM. How to log each code line of whosin action for memory usage ?

Apr 27 13:07:59 ip-10-136-100-100 rails[23132]: Oink Action: api/v1/sessions#checkupgrade
Apr 27 13:07:59 ip-10-136-100-100 rails[23132]: Memory usage: 397488 | PID: 23132
Apr 27 13:07:59 ip-10-136-100-100 rails[23132]: Oink Log Entry Complete
Apr 27 13:08:00 ip-10-136-100-100 rails[23132]: Oink Action: api/v1/rcfissues#search
Apr 27 13:08:00 ip-10-136-100-100 rails[23132]: Memory usage: 397488 | PID: 23132
Apr 27 13:08:00 ip-10-136-100-100 rails[23132]: Oink Log Entry Complete
Apr 27 13:08:00 ip-10-136-100-100 rails[23108]: Oink Action: api/v1/attendances#whosin
Apr 27 13:08:00 ip-10-136-100-100 rails[23108]: Memory usage: 471580 | PID: 23108
Apr 27 13:08:00 ip-10-136-100-100 rails[23108]: Oink Log Entry Complete

Optimally mine pictures from Instagram using Ruby on Rails

I want to optimally mine all the food pictures of a place once i give the Geo coordinates, does anyone know how to go about with this using Ruby on Rails & Instagram API?

Unicorn workers timeout after "zero downtime" deploy with capistrano

I'm running a Rails 3.2.21 app and deploy to a Ubuntu 12.04.5 box using capistrano (nginx and unicorn).

I have my app set for a zero-downtime deploy (at least I thought), with my config files looking more or less like these.

Here's the problem: When the deploy is nearly done and it restarts unicorn, when I watch my unicorn.log I see it fire up the new workers, reap the old ones... but then my app just hangs for 2-3 minutes. Any request to the app at this point hits the timeout window (which I set to 40 seconds) and returns my app's 500 error page.

Here is the first part of the output from unicorn.log as unicorn is restarting (I have 5 unicorn workers):

I, [2015-04-21T23:06:57.022492 #14347]  INFO -- : master process ready
I, [2015-04-21T23:06:57.844273 #15378]  INFO -- : worker=0 ready
I, [2015-04-21T23:06:57.944080 #15381]  INFO -- : worker=1 ready
I, [2015-04-21T23:06:58.089655 #15390]  INFO -- : worker=2 ready
I, [2015-04-21T23:06:58.230554 #14541]  INFO -- : reaped #<Process::Status: pid 15551 exit 0> worker=4
I, [2015-04-21T23:06:58.231455 #14541]  INFO -- : reaped #<Process::Status: pid 3644 exit 0> worker=0
I, [2015-04-21T23:06:58.249110 #15393]  INFO -- : worker=3 ready
I, [2015-04-21T23:06:58.650007 #15396]  INFO -- : worker=4 ready
I, [2015-04-21T23:07:01.246981 #14541]  INFO -- : reaped #<Process::Status: pid 32645 exit 0> worker=1
I, [2015-04-21T23:07:01.561786 #14541]  INFO -- : reaped #<Process::Status: pid 15534 exit 0> worker=2
I, [2015-04-21T23:07:06.657913 #14541]  INFO -- : reaped #<Process::Status: pid 16821 exit 0> worker=3
I, [2015-04-21T23:07:06.658325 #14541]  INFO -- : master complete

Afterwards, as the app hangs for those 2-3 minutes, here is what's happening:

E, [2015-04-21T23:07:38.069635 #14347] ERROR -- : worker=0 PID:15378 timeout (41s > 40s), killing
E, [2015-04-21T23:07:38.243005 #14347] ERROR -- : reaped #<Process::Status: pid 15378 SIGKILL (signal 9)> worker=0
E, [2015-04-21T23:07:39.647717 #14347] ERROR -- : worker=3 PID:15393 timeout (41s > 40s), killing
E, [2015-04-21T23:07:39.890543 #14347] ERROR -- : reaped #<Process::Status: pid 15393 SIGKILL (signal 9)> worker=3
I, [2015-04-21T23:07:40.727755 #16002]  INFO -- : worker=0 ready
I, [2015-04-21T23:07:43.212395 #16022]  INFO -- : worker=3 ready
E, [2015-04-21T23:08:24.511967 #14347] ERROR -- : worker=3 PID:16022 timeout (41s > 40s), killing
E, [2015-04-21T23:08:24.718512 #14347] ERROR -- : reaped #<Process::Status: pid 16022 SIGKILL (signal 9)> worker=3
I, [2015-04-21T23:08:28.010429 #16234]  INFO -- : worker=3 ready

Eventually, after 2 or 3 minutes, the app starts being responsive again, but everything is more sluggish. You can see this very clearly in New Relic (the horizontal line marks the deploy, and the light blue area indicates Ruby):

New Relic graph during and after deploy

I have an identical staging server, and I cannot replicate the issue in staging... granted, staging is under no load (I'm the only person trying to make page requests).

Here is my config/unicorn.rb file:

root = "/home/deployer/apps/myawesomeapp/current"
working_directory root

pid "#{root}/tmp/pids/unicorn.pid"
stderr_path "#{root}/log/unicorn.log"
stdout_path "#{root}/log/unicorn.log"

shared_path = "/home/deployer/apps/myawesomeapp/shared"

listen "/tmp/unicorn.myawesomeapp.sock"
worker_processes 5
timeout 40

preload_app true

before_exec do |server|
  ENV['BUNDLE_GEMFILE'] = "#{root}/Gemfile"
end

before_fork do |server, worker|
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.connection.disconnect!
  end

  old_pid = "#{root}/tmp/pids/unicorn.pid.oldbin"
  if File.exists?(old_pid) && server.pid != old_pid
    begin
      Process.kill("QUIT", File.read(old_pid).to_i)
    rescue Errno::ENOENT, Errno::ESRCH

    end
  end
end

after_fork do |server, worker|
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.establish_connection
  end
end

And just to paint a complete picture, in my capistrano deploy.rb, the unicorn restart task looks like this:

namespace :deploy do
  task :restart, roles: :app, except: { no_release: true } do
    run "kill -s USR2 `cat #{release_path}/tmp/pids/unicorn.pid`"
  end
end

Any ideas why the unicorn workers timeout right after the deploy? I thought the point of a zero-downtime was to keep the old ones around until the new ones are spun up and ready to serve?

Thanks!

UPDATE

I did another deploy, and this time kept an eye on production.log to see what was going on there. The only suspicious thing was the following lines, which were mixed in with normal requests:

Dalli/SASL authenticating as 7510de
Dalli/SASL: 7510de
Dalli/SASL authenticating as 7510de
Dalli/SASL: 7510de
Dalli/SASL authenticating as 7510de
Dalli/SASL: 7510de

After successfull sign up, call the sign in method of devise and pass required paramters to it

In my application I have used devise for registration purpose and it is working fine.

I have written another sign up method (I have to kept both the sign up methods) and able to register the user. Here is my code

new.html.haml

%h1 User Registration

= form_tag participant_user_registrations_path do
  = label_tag :full_name
  = text_field_tag :full_name

  = label_tag :address
  = text_area_tag :address, "", :rows => 5, :cols => 20

  = label_tag :mobile_number
  = text_field_tag :mobile_number

  = label_tag :email
  = text_field_tag :email

  = label_tag :slogan
  = text_area_tag :slogan, "", :rows => 5, :cols => 20

  = label_tag :password
  = password_field_tag :password

  = label_tag :activation_code
  = text_field_tag :activation_code

  = submit_tag "Sign Up", class: "btn btn-large btn-primary"

In my system username is auto-generated (we have a fixed format for it like full_name + mobile_no)

My user registration method

def another_registration
      @user = User.new(:client_id => 122,
                      :full_name => params["full_name"], 
                      :mobile_number => params["mobile_number"],
                      :address => params["address"],
                      :email => params["email"],
                      :participant_id => params["mobile_number"],
                      :status => "active",
                      :slogan => params["slogan"],
                      :password => params["password"])  
      if @user.save
        flash[:notice] = "User is saved"
      else
        flash[:alert] = @user.errors.full_messages.first #if @user.errors.any?
      end
    redirect_to :action => "new"
end

After successfully sign up I have to login the user account.

I have to use existing devise sign in functionality, so how can I call the devise sign in method and how to pass parameters to it.

Currently I am using username and password for the sign in.

ActiveAdmin Autocomplete dropdown select not working

I am using activeadmin 0.4.4 along with rails3-jquery-autocomplete 1.0.15.

I was able to add autocomplete to a field.The dropdown shows perfectly as required.

However I am not able to select a value from the dropdown. (If I manually write the value in the text field it works fine). I get this error in the browser console and I am unable to figure out on how to proceed with this:

Uncaught TypeError: undefined is not a function
t.railsAutocomplete.fn.extend.init.t.autocomplete.select  -- active_adimn.js line 13982

Please suggest.

dimanche 26 avril 2015

Rails rake db:create does not work

I come from a computer science and programming background, and I am familiar with a *nix CLI.

I am new to ruby on rails, and I am doing an online bootcamp. One of my lessons has me creating a new rails application. It starts out with the following commands to create a new rails application and create the database:

$ rails new bloccit -T
$ cd bloccit
$ rake db:create

When I run the rake command, the process just hangs. I let it run for 30 minutes, and it just sat there. When I do a hard interrupt, I get the following stack trace:

^C/Users/mikekeathley/.rvm/gems/ruby-2.2.1/gems/spring-1.3.4/lib/spring/client/run.rb:99:in `gets': Interrupt
from /Users/mikekeathley/.rvm/gems/ruby-2.2.1/gems/spring-1.3.4/lib/spring/client/run.rb:99:in `verify_server_version'
from /Users/mikekeathley/.rvm/gems/ruby-2.2.1/gems/spring-1.3.4/lib/spring/client/run.rb:56:in `run'
from /Users/mikekeathley/.rvm/gems/ruby-2.2.1/gems/spring-1.3.4/lib/spring/client/run.rb:37:in `warm_run'
from /Users/mikekeathley/.rvm/gems/ruby-2.2.1/gems/spring-1.3.4/lib/spring/client/run.rb:26:in `call'
from /Users/mikekeathley/.rvm/gems/ruby-2.2.1/gems/spring-1.3.4/lib/spring/client/command.rb:7:in `call'
from /Users/mikekeathley/.rvm/gems/ruby-2.2.1/gems/spring-1.3.4/lib/spring/client.rb:26:in `run'
from /Users/mikekeathley/.rvm/gems/ruby-2.2.1/gems/spring-1.3.4/bin/spring:48:in `<top (required)>'
from /Users/mikekeathley/.rvm/gems/ruby-2.2.1/gems/spring-1.3.4/lib/spring/binstub.rb:11:in `load'
from /Users/mikekeathley/.rvm/gems/ruby-2.2.1/gems/spring-1.3.4/lib/spring/binstub.rb:11:in `<top (required)>'
from /Users/mikekeathley/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from /Users/mikekeathley/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from /Users/mikekeathley/code/bloccit/bin/spring:13:in `<top (required)>'
from bin/rake:3:in `load'
from bin/rake:3:in `<main>'

I understand the stack trace: on line 99 in the run.rb file, the method gets is getting stuck. I just don't know anything about spring.

I am running Ruby 2.2.1p85, Rails 4.2.1, and sqlite3 1.3.10.

Thanks for any responses in advance!

add method to ActiveRecord::Base

I am reading rails guides. There is a example that I don't know how to do working. Can Someone to explain me how to do it working and what is the functionality of this example. I am newbie in rails

You can even create your own validation helpers and reuse them in several different models. For example, an application that manages surveys may find it useful to express that a certain field corresponds to a set of choices:

ActiveRecord::Base.class_eval do
  def self.validates_as_choice(attr_name, n, options={})
    validates attr_name, :inclusion => { { :in => 1..n }.merge!(options) }
  end
end

Simply reopen ActiveRecord::Base and define a class method like that. You’d typically put this code somewhere in config/initializers. You can usethis helper like this

class Movie < ActiveRecord::Base
  validates_as_choice :rating, 5
end

How can I retrieve this as hash?

I'm using this gem called youtube_search

Then I want to show 20 embed videos on my page.

Here's my code

<% @videos = YoutubeSearch.search('cats', :page => 1, :per_page => 20, 'orderby' => 'viewCount') %>

<% @videos.each do |video| %>
    <iframe src="http://ift.tt/1OUNE2I}" width=640 height=480 frameborder=0></iframe><br />
<% end %>

But this returns this error :(

ActionView::Template::Error (400 Bad Request):
    28: 
    29: <%#= YoutubeSearch.search('cats', :page => 1, :per_page => 20, 'orderby' => 'viewCount').first %>
    30: 
    31: <% @videos = YoutubeSearch.search('cats', :page => 1, :per_page => 20, 'orderby' => 'viewCount').first %>
    32: 
    33: <% @videos.each do |video| %>
    34: <iframe src="http://ift.tt/1OUNE2I}" width=640 height=480 frameborder=0></iframe><br />
  app/views/movies/index.html.erb:31:in `_app_views_movies_index_html_erb__3015092106786823575_115631080'
  app/controllers/movies_controller.rb:7:in `index'

How can I fix this?

How to avoid multiple users page acess at same time and same record in rails?

Would like to display a message when click any product edit page if somebody already opened/in that same record/page.

how to track users access on edit action for same record?ultimately i want to display message as "somebody already editing this product" to avoid overwrite process between multiple users.

please share your ideas on it.

Downloading and inserting phantomJS into executable path

I have been trying to download phantomJS for a few hours and I tried almost every solutions out there on the web to get this file downloaded. I am now using OS X Yosemite version 10.10.2. Can someone please give me a step by step process in which I can 1st Download the File 2nd insert the file into an executable Path Thanks A lot

samedi 25 avril 2015

callback before_save seems not working

I need execute the method name before the record is saved in the database, but it seems not working

class Guest < ActiveRecord::Base
  before_save :name
  has_and_belongs_to_many :checkins
  validates_presence_of :FirstName
  validates_presence_of :LastName
  validates_format_of :FirstName, with: /^[A-Za-z\s]+$/
  validates_format_of :LastName, with: /^[A-Za-z\s]+$/

  def name
    self.FirstName.titleize  + " " + self.LastName.titleize  
  end
end

console

=> Guest(id: integer, FirstName: string, LastName: string, age: integer, sex: string, photo: string, address: text, mobile: integer, email: string, birthdate: date, created_at: datetime, updated_at: datetime) 
1.9.3-p547 :008 > f=Guest.new
 => #<Guest id: nil, FirstName: nil, LastName: nil, age: nil, sex: nil, photo: nil, address: nil, mobile: nil, email: nil, birthdate: nil, created_at: nil, updated_at: nil> 
1.9.3-p547 :009 > f.FirstName=" fernando "
 => " fernando " 
1.9.3-p547 :010 > f.LastName=" suarez"
 => " suarez" 
1.9.3-p547 :011 > f.save
 => true 
1.9.3-p547 :012 > Guest.last
 => #<Guest id: 9, FirstName: " fernando ", LastName: " suarez", age: nil, sex: nil, photo: nil, address: nil, mobile: nil, email: nil, birthdate: nil, created_at: "2015-04-26 00:16:38", updated_at: "2015-04-26 00:16:38"> 

"undefined local variable or method `destroy_user_session_path'" (Authlogic)

I'm making a super basic rails app for practice, and I'm using Authlogic to implement user accounts. I've gotten so you can registr and log in but for some reason logging out isn't working. I get

undefined local variable or method `destroy_user_session_path' for #<#<Class:0x5bf5bd0>:0x41f19f0>

Extracted source:

10: <div id="user_nav">
11:    <% if current_user %>
12:       <%= link_to "Edit profile", edit_user_path(:current) %>
13:       <%= link_to "Logout(" + current_user.username + ")", destroy_user_session_path %>
14:    <% else %>
15:       <%= link_to "Register", new_user_path %>
16:       <%= link_to "Log in", new_user_session_path %>

I don't understand why it's not working, it's the default path made by resources isn't it? and "new_user_session_path" works fine. Here's my routing file:

Gnn::Application.routes.draw do
  get "users/new"

  get "users/edit"

  get "home/index"

  resources :categories

  resources :authors

  resources :users

  resources :user_sessions

  resources :articles do
    resources :comments 
  end

  # delete '/user_sessions/:id', to: 'user_sessions#destroy', as: 'logout'

  root :to => 'home#index'
end

I've tried manually creating the route with "delete '/user_sessions/:id', to: 'user_sessions#destroy'" and that didn't seem to work either. I'm at a standstill.

ActionController::ParameterMissing at /accounts/deposit tieing params to deposit form

I have been working on this rails 4 project since yesterday at 3pm and i have not slept. i am all out of ideas as to why this is bombing out. the error message i get is : ActionController::ParameterMissing at /accounts/deposit param is missing or the value is empty: affiliates_account

my accounts_controller looks like this:

class AccountsController < ApplicationController
#before_action :set_account, only: [:show, :edit, :deposit, :credit,     
:update, :destroy]
before_filter :set_account, only: [:show, :edit, :credit, :update, :destroy]
before_filter :authenticate_user!

respond_to :html

def index
 # @accounts = Account.all
 #@accounts = Account.where(id:current_user.id)
 if current_user.admin?
  @accounts = Account.all
  else
   @accounts = Account.where(email:current_user.email)
  end
  respond_with(@accounts)
  end

  def show
  if current_user.admin?
    @accounts = Account.all
   else
   @accounts = Account.where(email:current_user.email)
  end
  respond_with(@account)
  end

  def new
     @account = Account.new
     respond_with(@account)
  end

  def edit
    @accounts = Account.all
  end

  def create
    #  @account = Account.new(account_params)
    #@account.save
    # respond_with(@account)
  end

  def update
    @account.update(account_params)
    respond_with(@account)
  end

  def destroy
     @account.destroy
     respond_with(@account)
  end

  def withdrawl
    @account = Account.new(account_params)
    @account.email = current_user.email
    @account.user_id = current_user.id
  end

  def deposit
    @account = Account.new(account_params)
    @account.email = current_user.email
    @account.user_id = current_user.id
    respond_to do |format|
    @account.save
   end
     redirect_to :root
   end 


     private
     def set_account
        #@accounts = Account.where(id:current_user.id)
        @account = Account.find(params[:id])
     end

     def account_params
       # params[:account]
       params.require(:account).permit(:created_at, :email, :credit, :debit,
       :acctbal, :depotype)
     end
     end

and my Model for accounts.rb

 class Account < ActiveRecord::Base
 belongs_to :user
 validates :depotype, presence: true
 DEPOSIT_TYPES = [ "Check", "Credit card", "Purchase order" ]
 validates :depotype, inclusion: DEPOSIT_TYPES

 def final_acct_bal 
   accounts.to_a.sum {|account| account.final_acct_price}
   end
 end

and i created a new deposit.html.erb because the new.html.erb kept giving me a weird error and someone mention that the create method is tied to that and that i should create a seperate form page. so i did and now im having a tough time linking my deposit action method to that page so that my "add funds" button on my index.html.erb will go to it. and perform the requested actions accordingly.

<h1>Editing account</h1>

<%= render 'form' %>

<%= link_to 'Show', @account %> |
<%= link_to 'Back', accounts_path %>

my index.html.erb with that link_to button

<div class="container">
<h1>Listing Accounts Inquiries</h1>

<h2>Your Account information</h2>
  <table border="3">
    <table class="table table-striped">
        <thead>
            <tr>
                <th>Date</th>
                <th>Credit</th>
                <th>Debit</th>
                <th>Account Balance</th>
            </tr>
    </thead>
        <tbody>      
             <% @accounts.each do |account| %>   
                <tr>
                    <td><%= account.created_at %></td>
                    <td><b><font color="green"><%=
                         number_to_currency(account.credit)%></b></td>      
                    <td><b><font color="red"><%= 
                         number_to_currency(account.debit)%></font></b></td>    
                    <td><b><%= number_to_currency(account.acctbal)%></b>
               </td>        
                </tr>
                 <% end %>
            <tbody>     
        </table>
    </table>

    <%= link_to "Add Funds", deposit_accounts_path, method: :post, :class =>
       "btn btn-primary btn-sm" %>

    <table>
    <thead>
  <tr>
  <th colspan="3"></th>
  </tr>
  </thead>
     <% if can? :manage, Users%>
     <tbody>
       <% @accounts.each do |account| %>
      <tr>
    <td><%= link_to 'Show', account %></td>
    <td><%= link_to 'Edit', edit_account_path(account) %></td>
    <td><%= link_to 'Destroy', account, method: :delete, data: { confirm:
         'Are you sure?' } %></td>
       </tr>
    <% end %>
  </tbody>
  </table>

  <br>

   </div>
  <% end %>

i think this part of the params is hosing it up, params.require(:account) but i dont know what to do to change this so that it works and nothing else breaks

ActiveRecord query that groups by ID and sums rows

My Postgresql DB has this structure:

TABLE Orders
id (string)
userId (string)
value (integer)

This is an example of data:

id      userId      value
1       a@a.aaa     5
2       b@b.bbb     -1
3       a@a.aaa     -4
4       b@b.bbb     9

I want to do a query from ActiveRecord that sums all the values for a specific userId, like this:

a@a.aaa    1

My first approach is this one, but it doesn't work:

orders = Orders.where((:username => HERE_THE_USER_ID).sum(value)

How to request Paperclip attachment via faraday connection over http

I am making a get request via http to my other application. Both apps use Paperclip to manage attachment. How can I achieve to make the target app make a correct response with the attachment? Or any suggestion ?

vendredi 24 avril 2015

Rails jQuery File Upload for IE8

I basically followed RailsCasts #381 (jQuery File Upload) and #383 (Uploading to Amazon S3) to create a jQuery file upload solution for my app. It works great in Chrome, Firefox, Safari, and IE10. However, when I try it in IE8 the progress bar shows up empty/hollow and then nothing happens. Any help would be GREATLY appreciated.

My Form:

<%= s3_uploader_form post: 
wizard_path,
   as: "profile[image]" do %>
     <%= file_field_tag :file, multiple: false %>
<% end %>            

<script id="template-upload" type="text/x-tmpl">
  <div class="upload">
   {%=o.name%}
   <div class="progress">
    <div class="progress-bar progress-bar-success" style="width: 0%"></div>
   </div>
  </div>
</script>

My application.js file:

//= require jquery
//= require jquery_ujs
//= require jquery-fileupload/vendor/jquery.ui.widget
//= require jquery-fileupload/vendor/tmpl
//= require jquery-fileupload/vendor/load-image.all.min
//= require jquery-fileupload/vendor/canvas-to-blob
//= require jquery-fileupload/jquery.iframe-transport
//= require jquery-fileupload/jquery.fileupload
//= require jquery-fileupload/jquery.fileupload-process
//= require jquery-fileupload/jquery.fileupload-image
//= require jquery.validate.min
//= require jquery.dotdotdot.min
//= require jquery_nested_form
//= require placeholder
//= require bootstrap
//= require_tree .

My profile.js file:

jQuery(function() {
  return $('#fileupload').fileupload({
    dataType: 'json',
    // Enable image resizing, except for Android and Opera,
    // which actually support image resizing, but fail to
    // send Blob objects via XHR requests:
    disableImageResize: /Android(?!.*Chrome)|Opera/
        .test(window.navigator && navigator.userAgent),
    imageMinWidth: 153,
    imageMinHeight: 212,
    imageMaxWidth: 153,
    imageMaxHeight: 212,
    imageCrop: true,
    process: [
      {
        action: 'load',
        fileTypes: /^image\/(gif|jpeg|png)$/,
        maxFileSize: 4000000
      }, {
        action: 'resize',
      }, {
        action: 'save'
      }
    ],

    add: function(e, data) {
      var file, types, current_data;
      types = /(\.|\/)(gif|jpe?g|png)$/i;
      file = data.files[0];
      if (types.test(file.type) || types.test(file.name)) {
        current_data = $(this);

        // These 2 lines are from RC #381 (and are necessary for my progress bar to work)       
        data.context = $(tmpl("template-upload", file));    
        $('#fileupload').append(data.context);

        return data.process(function () {
          return current_data.fileupload('process', data);
        }).done(function() {
          return data.submit();
        });

      } else {
        return alert("" + file.name + " is not a gif, jpeg, or png image file");
      }
    },

      progress: function(e, data) {
        var progress;
        if (data.context) {
          progress = parseInt(data.loaded / data.total * 100, 10);
          return data.context.find('.progress-bar').css('width', progress + '%');
        }
      },

      done: function(e, data) {
        var content, domain, file, path, to;
        file = data.files[0];
        domain = $('#fileupload').attr('action');
        path = $('#fileupload input[name=key]').val().replace('${filename}', file.name);
        to = $('#fileupload').data('post');
        content = {};
        content[$('#fileupload').data('as')] = domain + path;
        jQuery.ajax({
          type: "PUT",
          url: to,
          data: content,
          dataType: "script",
        });
        if (data.context) {
          return data.context.remove();
        }
      },

      fail: function(e, data) {
        alert("" + data.files[0].name + " failed to upload.");
        console.log("Upload failed:");
        return console.log(data);
      }
    });

});

can not generate html output using rails 3

I have one issue.I am trying to render one select drop down value using rails 3.On the front page(UI) it is coming as per required but when i did view page source and checked it is not there.There is no html output generated but cannot understand how it is coming on UI.Please check my code below.

payment.html.erb:

<%= form_for :payment,:url => {:action => "check_type" },remote: true do |f| %>
    <div class="totalaligndiv">
      <div class="input-group bmargindiv1 col-md-6 pull-left"><span class="input-group-addon text-left"><div class="leftsidetextwidth">Type :</div></span>
      <%= f.select(:s_catagory,options_for_select([['Wood','Wood'],['Puja Samagree','Puja Samagree'],['Sweeper','Sweeper'],['Photo Grapher','Photo Grapher'],['Burning Assistant','Burning Assistant']],selected: "Type"),{},{:class => 'form-control',:onchange => ("$('#switch_car').submit()")}) %>
      </div>
      <div id="div_select" style="display:none">
      <div class="input-group bmargindiv1 col-md-6 pull-left" ><span class="input-group-addon text-left" ><div class="leftsidetextwidth">Select Vendor :</div></span>
      <div id="name-option">

      </div>
      </div>
      </div>
      <div class="clearfix"></div>
      <div class="tbpaddingdiv1 text-center">
        <%= f.submit "submit",:class => "btn btn-success",:id => "switch_car" %>
      </div>
    </div>
    <% end %>

payment_controller.rb:

class PaymentsController < ApplicationController
    def payment
        @payment=Vendor.new
        respond_to do |format|
            format.html 
            format.js
        end

    end
    def check_type
        flash[:notice]=params[:payment][:s_catagory]
        if  params[:payment][:v_name]
            flash[:notice]="hello"
        else
            @payment=Vendor.find_by_s_catagory(params[:payment][:s_catagory])
            @v_name=Vendor.where(:s_catagory =>params[:payment][:s_catagory] ).pluck(:v_name)
        end
    end
end

check_type.js.erb:

<% if @v_name %>
$("#div_select").css("display", "block");
$("#name-option").html("<%= escape_javascript (render 'nameoption' ) %>");
$("#name-option").slideDown(350);
<% end %>
<% if @vendor %>
console.log('hello');
$("#paymentdetail").css("display", "block");
$("#paymentoption").html("<%= escape_javascript (render 'paymentdetails' ) %>");
$("#paymentoption").slideDown(350);
<% end %>
$(".flash-message").html('<%= escape_javascript flash[:notice] %>');

_nameoption.html.erb:

<%= select_tag(:v_name,options_for_select(@v_name),{:class => "form-control"}) %>

Please help me to resolve this issue because i cannot execute the if part of check_type method in controller action.

Ruby how to test 2 dimension array element non blank

I am trying to test if the 2 dimension array element is non empty. the below code is failing

 <% if !subject["#{prefix}-addrline1"][index].empty ? %>

Thanks for your help!!

Capybara Rspec integration test link_to POST gives back ActionView::Template::Error:

It' my first time working with capybara and Rspec together for integration testing. I was able to link around a couple of routes and fill in the required fields from the form. Everything up to "visit webinars_path" in my spec works ok.

The trouble I am encountering is this line "click_link 'Register Now' " link. It gives me the error:

Failure/Error: find_link('Register Now', :href => '/webinars/test-webinar/register').click ActionView::Template::Error: undefined method `permalink' for nil:NilClass

I am assuming this means that @webinar is nil, however when I debug this in the Registration controller (see below registrations_controller.rb), using puts @webinar.permalink It logs back 'test-webinar' which is the webinar I want to register for. So, I know that registrations#new is passing, but it can't get past that to registraions#create. Can anyone help me solve this error, wondering why @webinar is nil.

register_for_webinar_spec.rb

require 'rails_helper'
require 'spec_helper'
require  'capybara/rspec'

feature 'Register for Webinar', :type => :feature do 

def create_webinar(options={})
    visit "/admin"
    click_link "Create Webinar"
    options[:name] ||= "Test Webinar"
    options[:permalink] ||= "test-webinar"
    options[:broadcast_date] ||= "2017-02-25 00:00:00"
    options[:gotowebinar_key] ||= "111-111-111"

    fill_in "webinar_name", with: options[:name]
    fill_in "webinar_permalink", with: options[:permalink]
    fill_in "webinar_broadcast_date", with: options[:broadcast_date]
    fill_in "webinar_gotowebinar_key", with: options[:gotowebinar_key]

    click_button "Create"
 end

 def register_attendee(options={})
    find_link('Register Now', :href => '/webinars/test-webinar/register').click

    options[:first_name] ||= "John"
    options[:last_name] ||= "Doe"
    options[:company] ||= "JD CO"
    options[:email] ||= "John_Doe@gmail.com"

    fill_in "attendee_first_name", with: options[:first_name]
    fill_in "attendee_last_name", with: options[:last_name]
    fill_in "attendee_company", with: options[:company]
    fill_in "attendee_email", with: options[:email]
 end 

scenario 'registers attendee to webinar' do 
    create_webinar
    expect(page).to have_content("New Webinar is Created")

    visit webinars_path
    register_attendee

end 

end

registrations_controller.rb

require 'json'
require 'net/http'
class RegistrationsController < ApplicationController

def new
  get_webinar
  get_webinar_details

  @attendee = Attendee.new
  puts @webinar.permalink
end

def create
  get_webinar


  @attendee =  Attendee.new(attendee_params)
  @attendee.webinar = @webinar

  if @attendee.save
    redirect_to registration_path(@webinar.permalink)
  else
    flash[:error] = @attendee.errors

    get_webinar_details
    render 'new'
  end
end

def show
  get_webinar
  @webinars = Webinar.where.not(video_url: '').order('broadcast_date DESC')
end

private

def attendee_params
  params.require(:attendee).permit(:first_name, :last_name, :email, :company, :webinar_id, :ip_address, :address, :latitude, :longitude)
end
end

webinar index.html

<% if @broadcast_webinars.exists? %>
  <% @broadcast_webinars.each do |webinar| %>
  <%= link_to webinar_path(webinar.permalink) do %>
  <div class="webinar-container centered upcoming all" data-category="upcoming">
    <% end %>
    <div class="left-section"></div>
    <div class="middle-section">
      <h3><%= webinar.name%></h3>
      <span class="posted-date"><strong><%= webinar.broadcast_date.strftime("%A") %>, &nbsp;<%= webinar.broadcast_date.strftime("%d") %>&nbsp;<%= webinar.broadcast_date.strftime("%B") %> &nbsp;<%= webinar.broadcast_date.strftime("%Y") %></strong></span>
      <div class="info centered">
        <i class="fa fa-play-circle"></i>
      </div>
        <p><%= webinar.description %></p>
        <a href=<%= register_path(webinar.permalink) %>><button>Register Now </button></a>
    </div>
    <div class="right-section">
      <p><span><%= webinar.broadcast_date.strftime("%d") %></span><br><span><%= webinar.broadcast_date.strftime("%B") %></span>
    </div>
    <div class="bottom-section">
      <div class="bottom-1">
        <p> 
          <% if webinar.duration != ""%>
          <%= webinar.duration %> mins
          <% end %>
        </p>
      </div>
      <div class="bottom-2">
        <p class="author"><span><i class="fa fa-user"></i>AUTHORS:</span><%= webinar.author%> 
          <% if webinar.author2 != ""%>
          , <%= webinar.author2%></p>
          <% end %>
      </div>
      <div class="bottom-3">
        <p class="tags"><span><i class="fa fa-tags"></i></span><%= webinar.tag %></p>
      </div>
      </div>
    </div>
  <% end %>
<% end %>

JSON object causing exception with Rails JSON.decode

The JSON object below causes ActiveSupport::JSON.decode to throw the exception below. What causes this?

Exception:

795: unexpected token at ''
/usr/local/lib/ruby/gems/1.9.1/gems/json-1.8.1/lib/json/common.rb:155:in `parse'
/usr/local/lib/ruby/gems/1.9.1/gems/json-1.8.1/lib/json/common.rb:155:in `parse'
/usr/local/lib/ruby/gems/1.9.1/gems/multi_json-1.9.2/lib/multi_json/adapters/json_common.rb:16:in `load'
/usr/local/lib/ruby/gems/1.9.1/gems/multi_json-1.9.2/lib/multi_json/adapter.rb:20:in `load'
/usr/local/lib/ruby/gems/1.9.1/gems/multi_json-1.9.2/lib/multi_json.rb:121:in `load'
/usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.2.12/lib/active_support/json/decoding.rb:15:in `decode'

JSON object (from http://ift.tt/1Ke3BAu):

{
 "resultCount":1,
 "results": [
{"artistViewUrl":"http://ift.tt/1z2p4eK", "artworkUrl60":"http://ift.tt/1Ke3DIl", 
"screenshotUrls":["http://ift.tt/1Ke3DIp", "http://ift.tt/1z2p5zi", "http://ift.tt/1Ke3BQI", "http://ift.tt/1z2p4v3"], "ipadScreenshotUrls":[], "artworkUrl512":"http://ift.tt/1Ke3BQK", "kind":"software", "features":[], 
"supportedDevices":["iPadFourthGen4G", "iPhone6", "iPad23G", "iPhone5s", "iPadMini", "iPhone6Plus", "iPad2Wifi", "iPhone4S", "iPhone5", "iPadFourthGen", "iPhone4", "iPodTouchFifthGen", "iPadThirdGen", "iPadThirdGen4G", "iPadMini4G", "iPhone5c"], "advisories":[], "isGameCenterEnabled":false, "trackCensoredName":"Periscope", "trackViewUrl":"http://ift.tt/1Ke3BQM", "contentAdvisoryRating":"4+", "artworkUrl100":"http://ift.tt/1Ke3BQK", "languageCodesISO2A":["NB", "CA", "CS", "DA", "NL", "EN", "FR", "DE", "EL", "ID", "IT", "JA", "KO", "NN", "PL", "PT", "RU", "ZH", "ES", "SV", "ZH", "TR", "UK", "VI"], "fileSizeBytes":"15090739", "sellerUrl":"https://periscope.tv", "averageUserRatingForCurrentVersion":3.5, "userRatingCountForCurrentVersion":166, "trackContentRating":"4+", "currency":"USD", "wrapperType":"software", "version":"1.0.2", 
"description":"Periscope lets you broadcast live video to the world. Going live will instantly notify your followers who can join, comment and send you hearts in real time. The more hearts you get, the higher they flutter on the screen.\n\nOther features:\n[+] REPLAY: When your broadcast is over, you can make it available for replay so viewers can watch later. Viewers can replay your broadcast with comments and hearts to relive the full experience. Replays currently last 24 hours. You can delete your replay at any time.\n[+] PRIVATE: If you want to broadcast to specific people, press the lock icon before going live and choose who you want to invite to your broadcast. \n[+] TWITTER: You can choose to share your Periscope broadcasts on Twitter by tapping the bird icon before you start broadcasting. When you go live, you’ll tweet a link so that your Twitter followers can watch on the web (or in the app)\n[+] MANAGE NOTIFICATIONS: Periscope will suggest people for you to follow based on your Twitter network. You can always follow new people, or unfollow them if you don’t want to be notified when they go live. You can also adjust notification preferences in Periscope Settings (in Profile)\n[+] HEARTS: Periscope keeps track of how many hearts you get from your viewers. The more hearts, the higher you get in the “Most Loved” list.", "artistId":296415947, "artistName":"Twitter, Inc.", "genres":["Social Networking"], "price":0.00, "bundleId":"com.bountylabs.periscope", "genreIds":["6005"], "releaseDate":"2015-03-26T07:01:50Z", "sellerName":"Twitter, Inc.", "trackName":"Periscope", "trackId":972909677, "primaryGenreName":"Social Networking", "primaryGenreId":6005, 
"releaseNotes":"- New ‘Global’ section added to Periscope that lists the most recent, live broadcasts from around the world. Your home feed will only show live broadcasts and replays tailored to you.\n- A new “Follower Only” mode is available before starting your broadcast. If you turn this on, only viewers that YOU follow can comment in your broadcast.\n- Users who are verified are marked by the classic Twitter Verified badge you’re used to seeing.\n- Major scrolling performance improvements. This will feel silky and smooth compared to the last version!\n- You can block users more easily (tap on a comment to present the option to block)\n- Fixed a bug where viewers & broadcasters would sometimes stop seeing comments and hearts.\n- Fixed a caching issue where the wrong Profile image would get displayed for a user\n- Fixed a bug where some iOS 7 users couldn’t watch broadcasts with kajillions of viewers", "minimumOsVersion":"7.1", "formattedPrice":"Free", "userRatingCount":949, "averageUserRating":3.5}]
}