Tuesday, June 28, 2016

Cohort analysis using pgsql/activerecord | Fixed issues

Cohort analysis using pgsql/activerecord | Fixed issues


Cohort analysis using pgsql/activerecord

Posted: 28 Jun 2016 07:57 AM PDT

I'm performing a cohort analysis on a single table messages. I need to calculate the retention rates of users that created a message (day_0), also created a message on the following day, day after, etc (day_1, day_2, etc).

I was previously doing most of the processing post-query in ruby iterations. Now I have larger tables to deal with. It's way too slow and memory intensive in ruby so I need to offload the heavy lifting to the DB. I've also tried the cohort_me gem and experienced poor performance.

I don't have much experience with SQL w/out activerecord. Here's what I have so far:

SELECT   date_trunc('day', messages.created_at) as day,  count(distinct messages.user_id) as day_5_users  FROM   messages  WHERE   messages.created_at >= date_trunc('day', now() - interval '5 days') AND   messages.created_at < date_trunc('day', now() - interval '4 days')  GROUP BY 1  ORDER BY 1;  

This returns the count of users who created messages five days ago. Now I need to find the count of THOSE users who created messages the following day, day after that, etc. until the current day.

I need to perform this same analysis on different base days. So next instead of 5 days go, it starts the analysis at 4 days ago as the base day.

Can this be done with one query?

Implementing .each in Wicegrid (Ruby on Rails)

Posted: 28 Jun 2016 07:54 AM PDT

I have the following column in my Wicegrid table, which iterates through the advisors of a student and lists them in the Wicegrid:

g.column name: 'Student Advisor' do |user|    res=''    if user.advisors      user.advisors.each do |advisor|        advisor.username      end    end   end  

Wicegrid doesn't allow arrays to be returned inside their columns or at least that is what I understood from the error below:

"When WiceGrid column block returns an array its second element is expected to be a hash containing HTML attributes for the tag."

Is there another way to have the list of advisors in the table?

CSS animation not working in Rails app

Posted: 28 Jun 2016 07:46 AM PDT

So I have a button that I want to auto-hide when the user scrolls down the page and show when the user scrolls up. Below are the codes:

application.js

// This is a manifest file that'll be compiled into application.js, which will include all the files  // listed below.  //  // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,  // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.  //  // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the  // compiled file.  //  // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details  // about supported directives.  //  //= require jquery  //= require jquery_ujs  //= require bootstrap-sprockets  //= require turbolinks  //= require_tree .  //= require jquery.infinitescroll  

index.html.haml

%a.scrollToTop{:href => "#"}  

autohide.js

$(document).ready(function(){      var prev = 0;    var $window = $(window);    var bar = $('.scrollToTop');      $window.on('scroll', function(){      var scrollTop = $window.scrollTop();      bar.toggleClass('hidden', scrollTop > prev);        prev = scrollTop;    });    });  

application.css.scss

/*   *= require_tree .   *= require_self   */    // "bootstrap-sprockets" must be imported before "bootstrap" and "bootstrap/variables"  @import "bootstrap-sprockets";  @import "bootstrap";      .scrollToTop{    width:70px;    height:70px;    background: #fff;    font-weight: bold;    position:fixed;    bottom:20px;    right:20px;    border-radius:50%;    box-shadow: 0 2px 5px rgba(0,0,0,0.12), 0 2px 4px rgba(0,0,0,0.24);    -webkit-transform: translateZ(0);    transition: transform 1s  }    .scrollToTop:hover{    box-shadow: 0 10px 20px rgba(0,0,0,0.25), 0 8px 8px rgba(0,0,0,0.22);    -webkit-transition: all 0.4s ease-in-out;    -moz-transition: all 0.4s ease-in-out;    -o-transition: all 0.4s ease-in-out;    transition: all 0.4s ease-in-out;  }    .scrollToTop.hidden{    transform: translateY(100px);  }  

The code works fine; the button does hide/show depending on the scroll direction. But the problem is, it doesn't animate i.e. it instantaneously hides and shows instead of sliding up and down. Any idea what's causing this? Thanks in advance!

Run a Rails job at precise time (accurate to the second)

Posted: 28 Jun 2016 07:40 AM PDT

I'm making an application that needs to run a job at extremely precise intervals of time (say 30 seconds, maximum acceptable delay is +-1 second).

I'm currently doing so using an external Go application that polls an API endpoint built within my application.

Is there a way that I could run the task on a worker machine (eg a Heroku dyno) with delays less than one second?

I've investigated Sidekiq and delayed_job, but both have significant lag and therefore are unsuitable for my application.

omniauth instagram oauth2 code 400

Posted: 28 Jun 2016 07:34 AM PDT

this is my gem file :

gem 'omniauth-oauth2', '1.4'  gem 'omniauth-instagram', github: 'ropiku/omniauth-instagram'  

omniauth.rb file :

Rails.application.config.middleware.use OmniAuth::Builder do  provider :instagram, ENV['Client ID'], ENV['secret']  end  

this is sesstion.rb

class SessionsController < ApplicationController  def new  redirect_to '/auth/instagram/'  end     def create  auth = request.env["omniauth.auth"]  user = User.where(:provider => auth['provider'],                    :uid => auth['uid'].to_s).first || User.create_with_omniauth(auth)  reset_session  session[:user_id] = user.id  redirect_to root_url, :notice => 'Signed in!'    end     def destroy  reset_session  redirect_to root_url, :notice => 'Signed out!'   end      def failure       redirect_to root_url, :alert => "Authentication error: #{params[:message].humanize}"    end     end  

but when i click on sign in i face this error

{"code": 400, "error_type": "OAuthException", "error_message": "You must include a valid client_id, response_type, and redirect_uri parameters"}  

and this is url : https://www.instagram.com/oauth/authorize?client_id&redirect_uri=http://localhost:3000/auth/instagram/callback&response_type=code&scope=basic&state=955173070b58f0de9affcdb30c0da27d836683b922542db1

what is my problem ?

fonts and images and not loading

Posted: 28 Jun 2016 07:43 AM PDT

I have deploy my application on AWS with nginx and passenger .My images, fonts and icons are not loading .I have look for the possible solution on internet like config.assets.compile = true and did RAILS_ENV = 'production' rake assets:precompile but nothing working for me

Difference between ActiveRecord::Base.connection and find_by_sql

Posted: 28 Jun 2016 07:31 AM PDT

I need to perform some custom queries on my rails application and was wondering wich approach is better:

results = ActiveRecord::Base.connection.execute(query)  

Or

Model.find_by_sql(query)  

Been reading the documentation but didn't really get how they perform.

Ajax request to rails controller is setting the id parameter = "destroy"?

Posted: 28 Jun 2016 07:31 AM PDT

so I have a weird problem where for some reason the id parameter in my delete request is being set to "destroy". Here is the code for my ajax request

function deleteItems(id_data, table){    $.ajax({      url: '/items/destroy',      method: 'DELETE',      processData: true,      data: {ids: id_data },      success: function(){       dropItems(id_data, table)      }    });   }  

And here are the parameters I am getting in the rails controller

{"ids"=>["6", "19"], "controller"=>"items", "action"=>"destroy", "id"=>"destroy"}  

If I try and set the data key to id (instead of id's) I get this

{"id"=>"destroy", "controller"=>"items", "action"=>"destroy"}  

Any help in figuring out why id is being set to "destroy" would be awesome. Thanks

How to use ruby uniq on nested array/hash

Posted: 28 Jun 2016 07:37 AM PDT

I am trying to call the uniq method on the follow json so that it would only return unique result base on employee_id

# Json array  a ={    results: [     {      employee: {        name: "A",        employee_id: "A-00016",        title: 1       }     },{      employee: {        name: "A",        employee_id: "A-00016",        title: 2       }     },{      employee: {        name: "C",        employee_id: "C-00017",        title: 3       }      }     ]    }        # Calling uniq on a  a.uniq { |p| p.values_at(:employee_id) }  

However, I am only getting this result

{    results: [     {      employee: {        name: "A",        employee_id: "A-00016",        title: 1       }      }     ]    }  

Instead of what I want

{    results: [     {      employee: {        name: "A",        employee_id: "A-00016",        title: 1       },{      employee: {        name: "C",        employee_id: "C-00017",        title: 3       }      }     ]    }  

Am I using the correct method to output the result I want?

How to read from Rails cache atomically

Posted: 28 Jun 2016 07:17 AM PDT

I have 2 processes running. The user action that basically does this:

      Rails.cache.fetch("items/#{self.id}/default_as_json") do          super(root: false,                :only => get_only_show,                :methods => get_include_methods          )        end  

On page load

Then I have another process, that does not run as often. Maybe once every 2 weeks, but it runs for a couple hours.
This process is doing a lot of data processing and after a lot of testing the best option I came up with was just to clear the entire cache after each step. So the website served the most up to date information. The performance cost of this is not much of an issue.
I am essentially running into a race condition on page load. It seems like it is finding the existence of the key, but by the time it goes to read the key the file has been deleted.
This is the stack trace I am seeing when this happens:

ActionView::Template::Error (No such file or directory @ rb_sysopen - [CACHE_LOCATION]/A95/DD0/.permissions_check.70057658850120.4451.366289):      43:       <% if object_type == "Item" %>      44:         <%= render(      45:           partial: 'items/no_table_row',      46:           locals: {object: this_object.as_json,      47:                   singlesearch: true}      48:         ) %>      49:       <% elsif object_type == "Ability" %>    app/models/item.rb:202:in `serializable_hash'    app/views/poly_single_searches/_search_list.html.erb:46:in `block in _app_views_poly_single_searches__search_list_html_erb__1164541304050581354_70057643074520'    app/views/poly_single_searches/_search_list.html.erb:35:in `_app_views_poly_single_searches__search_list_html_erb__1164541304050581354_70057643074520'    app/views/poly_single_searches/fetch_search.html.erb:1:in `_app_views_poly_single_searches_fetch_search_html_erb___2217227932112086773_70057643107440'    app/controllers/poly_single_searches_controller.rb:14:in `fetch_search'        Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (0.8ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (1.0ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb (7.5ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/_markup.html.erb (0.6ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.5ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.7ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.5ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/console.js.erb within layouts/javascript (11.0ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/main.js.erb within layouts/javascript (0.3ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.4ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/index.html.erb (26.0ms)  

When this other process is not running, everything works perfectly. I have it as a task to figure out a better way to clear caching, right now not clearing the cache after each step is not an option.
One solution I have is wrapping the Rails.cache.fetch in a rescue for this however that may just keep failing until it manages to run fast enough.

Errno::EMFILE (Too many open files - socket(2)) when using RedisStore for caching while running in Passenger

Posted: 28 Jun 2016 07:11 AM PDT

My application is using the redis store, which works fine locally, but in production, using Phusion Passenger (open source) I run into this error.

Errno::EMFILE (Too many open files - socket(2)):  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:24:in `initialize'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:24:in `initialize'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:143:in `new'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:143:in `connect_addrinfo'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:187:in `block in connect'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:185:in `each'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:185:in `each_with_index'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:185:in `connect'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:260:in `connect'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:336:in `establish_connection'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:101:in `block in connect'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:293:in `with_reconnect'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:100:in `connect'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:364:in `ensure_connected'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:221:in `block in process'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:306:in `logging'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:220:in `process'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:120:in `call'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis.rb:862:in `block in get'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis.rb:58:in `block in synchronize'  /usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis.rb:58:in `synchronize'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis.rb:861:in `get'  vendor/bundle/ruby/2.2.0/gems/redis-store-1.1.7/lib/redis/store/interface.rb:5:in `get'  vendor/bundle/ruby/2.2.0/gems/redis-store-1.1.7/lib/redis/store/marshalling.rb:17:in `get'  vendor/bundle/ruby/2.2.0/gems/redis-activesupport-4.1.5/lib/active_support/cache/redis_store.rb:230:in `block in read_entry'  vendor/bundle/ruby/2.2.0/gems/redis-activesupport-4.1.5/lib/active_support/cache/redis_store.rb:212:in `call'  vendor/bundle/ruby/2.2.0/gems/redis-activesupport-4.1.5/lib/active_support/cache/redis_store.rb:212:in `with'  vendor/bundle/ruby/2.2.0/gems/redis-activesupport-4.1.5/lib/active_support/cache/redis_store.rb:230:in `read_entry'  vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.6/lib/active_support/cache.rb:413:in `block in exist?'  vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.6/lib/active_support/cache.rb:547:in `block in instrument'  vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.6/lib/active_support/notifications.rb:166:in `instrument'  vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.6/lib/active_support/cache.rb:547:in `instrument'  vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.6/lib/active_support/cache.rb:412:in `exist?'  vendor/bundle/ruby/2.2.0/gems/redis-activesupport-4.1.5/lib/active_support/cache/redis_store.rb:200:in `exist?'  

My cache initialization code is

Rails.application.configure do      Rack::MiniProfiler.config.storage_options = { host: 'redis.local.com', port: 6379 }      Rack::MiniProfiler.config.storage = Rack::MiniProfiler::RedisStore      config.cache_store = :redis_store, http://redis.local.com:6379, { expires_in: 5.minutes }      Rails.cache = ActiveSupport::Cache::RedisStore.new  end  

Having searched all over the redis-rb and redis-store gems, hasn't turned up anything at all. How do I ensure passenger does not create multiple connections to Redis when using it as cache store?

Multisearch pg_search with Rails

Posted: 28 Jun 2016 07:29 AM PDT

I have a question about multi field search using pg_search gem. What I want to do is make a query in multiples fields, so I have the following code in my Client model:

  pg_search_scope :search,      :against => [:name, :email],      :using => [:trigram, :tsearch],      :ignoring => :accents  

For testing I have:

Client 1

name: "Anna"

email: "mycompany@foo.com"

Then I searched with Client.search("anna") and no results are returned. Or Client.search("nna") also no results found.

Any suggestion here ?

Thanks in advance.

Update 1

I set the threshold manually and it works:

  pg_search_scope :search,      :against => [:name, :email],      using: {              tsearch: {},              trigram:    {threshold:  0.1}             }  

Authenticating on two different backend servers

Posted: 28 Jun 2016 07:15 AM PDT

Due to requirement changes we need to add a node server to our already existing system. We will be using sails.js for the realtime communication part of the app and redis store for session management. But the confusion now is what is the best way to authenticate the client app/user on both servers with one login form.

Any help will be much appreciated.

Ruby on Rails: is there an ideal app directory structure in Windows

Posted: 28 Jun 2016 06:59 AM PDT

Just a quick question from a Rails learner. As I understand it, it is not necessary to place a new Rails app inside the directory where Ruby and Rails are installed. But, is there an ideal place for apps? What are experienced developers using?

I ask this, because I may have misplaced a previous app, hidden somewhere deep in a directory structure; and, strange as it might seem to most of you, I cannot find where the older app is. I have quite some problems searching in Windows 10; it is a nightmare, compared to how it was in Windows XP.

Setting default value for Rails select helper block

Posted: 28 Jun 2016 07:27 AM PDT

How can I set default value in Rails select helper block?

<div class="field">    <label>Gender</label>    <%= f.select :gender, [], { prompt: 'Select gender', selected: 'Female' }, { :class => 'ui selection dropdown' } do %>      <% Subject.genders.keys.each do |c| %>        <%= content_tag(:option, value: c, class: 'item') do %>          <%= content_tag(:i, '', class: "#{c.downcase} icon") %>          <%= content_tag(:span, c) %>        <% end %>      <% end %>    <% end %>  </div>  

I tried setting it with :selected option but it doesn't work.

Convert String to DateTime Ruby

Posted: 28 Jun 2016 07:27 AM PDT

I have a string "2015-11-01T10:00:00.00+08:00" extracted from json response. How can convert it to Time or DateTime?

I tried Time.new("2015-11-01T10:00:00.00+08:00") its returning 2015-01-01 00:00:00 +0530, clearly the date is changed here and time too.

Rails/AJAX cached form submission - 422 unprocessable entity

Posted: 28 Jun 2016 06:14 AM PDT

My Rails app features a public-facing form that passes user input to the controller as a stringified JSON via AJAX. The form is designed for offline use, and so every visit to the form page other than the first is served from the browser cache (using the cache manifest). I am having an issue where the form submission returns a 422 unprocessable entity error unless the browser history has been cleared before navigating to the form page... that is to say that a user can only make one form submission, all subsequent submissions are 422 unless they clear the history and return to the form to refresh the cache. Unfortunately, that's not going to fly.

I am not tremendously experienced with Rails security, but I am under the impression that this has to do with CSRF protection and the fact that, for any visit to the form page other than the first, a stale CSRF token is being passed.

My AJAX request appears like so:

$.ajax({      url: "post/submission",      type: "POST",      dataType: "json",      beforeSend: function(xhr) {xhr.setRequestHeader("X-CSRF-Token", $("meta[name='csrf-token']").attr("content"))},      data: {"post" : postParameter},      success: function(response){          window.location = '/post/approval';      }  });  

At the moment, the layout page includes the <%= csrf_meta_tags %>, and I have the standard protect_from_forgery with: :exception in the application controller.

The final structural element to note about this form is that, although the form itself is public-facing, it requires a user login after the submit button is clicked - so a submission will not be successful without a valid login.

Is there a safe way that I can get around this problem? I'm sure it goes without saying, but I can't have my users clearing their history and re-caching the form after every submission.

Rails, rollback on trying to create an instance of a model with multiple belongs_to

Posted: 28 Jun 2016 06:13 AM PDT

I have a class "Localization". "Articles" have many localizations. This worked perfectly until I created a model Event and tried to add localizations to that too.

My localization class

class Localization < ApplicationRecord      belongs_to :event      belongs_to :article      belongs_to :language  end  

My article class

class Article < ApplicationRecord      has_many :localizations, dependent: :destroy      mount_uploader :image, ImageUploader      enum article_type: [:news, :catalog, :notifs]  end  

My event class

 class Event < ApplicationRecord      has_many :localizations, dependent: :destroy      mount_uploader :image, ImageUploader  end  

My localizations table creation

create_table :localizations do |t|        t.integer :article_id        t.integer :event_id        t.integer :language_id        t.string :title        t.text :text        t.timestamps      end  

When I try to create an item of either Article or Event I get a rollback:

SQL (1.3ms)  INSERT INTO "articles" ("created_at", "updated_at", "article_type") VALUES ($1, $2, $3) RETURNING "id"  [["created_at", 2016-06-28 13:08:36 UTC], ["updated_at", 2016-06-28 13:08:36 UTC], ["article_type", 0]]     (11.5ms)  COMMIT    Localization Load (0.8ms)  SELECT  "localizations".* FROM "localizations" WHERE "localizations"."article_id" = $1 AND "localizations"."language_id" = $2 LIMIT $3  [["article_id", 4], ["language_id", 1], ["LIMIT", 1]]     (0.2ms)  BEGIN    Language Load (0.3ms)  SELECT  "languages".* FROM "languages" WHERE "languages"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]     (0.3ms)  ROLLBACK  

What am I doing wrong?

How to import a postgis db on heroku with rails

Posted: 28 Jun 2016 06:11 AM PDT

How to correctly import a postgres 9.4 + postgis 2.1 database on Heroku with rails ?

They have beta support for postgis, however I tried using pg:push as they documented, but it throws a warning about needing to be a sudo user to create postgres operators.

Moreover I can't be sure the complex data I have (multipolygons) is correctly copied during the process. Is there a specific process to follow for postgis ?

Thanks.

How to keep same order on each session?

Posted: 28 Jun 2016 06:15 AM PDT

I'm working on a store in rails. As I'm new to Rails I was following some tutorial on how to create a shopping cart and ordering system.

So right now orders with unique ids are being created and saved by a user, automatically, upon addition of a order_item to a cart on each new session. And this is the issue.

I want order to persist until 30 days passes (the one order that is created first, that is, when first order_item has been added by a user). The problem is next: So if user adds order_items, he creates an order and then logs out and comes back and adds a new order_item to his cart, new order is being created even though there is already his older order saved to database. I want to retrieve that first order.

Can you please tell me how to achieve this?

class OrderItemsController < ApplicationController    def create      @order = current_order      @order_item = @order.order_items.new(order_item_params)      @order.user_id = current_user.id      @order.save      session[:order_id] = @order.id      respond_to do |format|      format.js { flash[:notice] = "ORDER ITEM HAS BEEN ADDED." }     end    end  

order_item.rb

class OrderItem < ActiveRecord::Base    belongs_to :product    belongs_to :order    validates_associated :order    validates :quantity, presence: true, numericality: { only_integer: true, greater_than: 0 }    validate :product_present    validate :order_present        before_save :finalize      def unit_price      if persisted?        self[:unit_price]      else        product.price      end    end      def total_price      unit_price * quantity    end    private    def product_present      if product.nil?        errors.add(:product, "is not valid or is not active.")      end    end      def order_present      if order.nil?        errors.add(:order, "is not a valid order.")      end    end      def finalize      self[:unit_price] = unit_price      self[:total_price] = quantity * self[:unit_price]    end      end  

order.rb

class Order < ActiveRecord::Base    belongs_to :order_status    belongs_to :user    has_many :order_items    validates_length_of :order_items, maximum: 3    before_create :set_order_status    before_save :update_subtotal          def subtotal      order_items.collect { |oi| oi.valid? ? (oi.quantity * oi.unit_price) : 0 }.sum    end  private    def set_order_status      self.order_status_id = 1    end      def update_subtotal      self[:subtotal] = subtotal    end        end  

user.rb

has_many :order  

Initialize Ruby codes error

Posted: 28 Jun 2016 06:33 AM PDT

I tried to run these codes:

class Dog         def set_name(name)        @dogname = name     end       def get_name        return @dogname     end       def talk        return "awww"     end       def initialize(title, description)        @title = title        @description = description     end      end    doggy = Dog.new  doggy.set_name('Sam')  puts doggy.get_name  puts doggy.talk      bogart = Dog.new('The Book', 'The road not taken')  puts bogart.to_s  puts bogart.inspect  

I did make sure every argument is correct. However, I got the following errors.

C:\Ruby200\bin\ruby.exe -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) C:/Users/Todd/RubymineProjects/untitled1/test.rb  C:/Users/Todd/RubymineProjects/untitled1/test.rb:15:in `initialize': wrong number of arguments (0 for 2) (ArgumentError)      from C:/Users/Todd/RubymineProjects/untitled1/test.rb:22:in `new'      from C:/Users/Todd/RubymineProjects/untitled1/test.rb:22:in `<top (required)>'      from -e:1:in `load'      from -e:1:in `<main>'    Process finished with exit code 1  

Tried my best can't find the issue. Any idea where I miss?

Webmock stub request not working

Posted: 28 Jun 2016 06:16 AM PDT

I need to make a request to facebook throw an error, so that I can ensure my circuit breaker is working.

My test is this

context 'when Facebook API is not responding' do    before(:each) do      stub_request(:get, 'facebook.com/*')        .with(headers: { 'Accept' => '*/*', 'Content-Type' => 'application/json', 'User-Agent' => 'Faraday v0.9.2' })        .to_raise(StandardError)    end      it 'should return error code 40' do      3.times { post :create, valid_params }      expect(Oj.load(response.body)['code']).to be_eql '40'    end      it 'message should say that Facebook is not answering' do      3.times { post :create, valid_params }      expect(Oj.load(response.body)['error']) =~ 'not answering'    end  end  

If I configure VCR like this:

c.allow_http_connections_when_no_cassette = true  

the tests does not pass, and I see even with the stub_request, the app calls Facebook endpoints.

If I change allow_http_connections_when_no_cassette to false, it throws an error and trips my circuit breaker

Switching facebook_user_data from green to red because VCR::Errors::UnhandledHTTPRequestError

Although with the circuit tripped the tests pass, it is not the correct exception thrown.

Testing Angular CoffeeScript with vanilla JS?

Posted: 28 Jun 2016 05:03 AM PDT

I'm about to inherit a somewhat mature Rails monolith for work. The previous maintainers chose to write Angular JS controllers and whatnot in CoffeeScript, served through the Rails asset pipeline. I prefer regular old JS because I hate having to 'translate' documentation just to hope that it compiles to the right JS.

I also lack tests. No mocha, no jasmine, no capybara, nada.

Before I jump in and start converting the Coffee to JS file by file, I would like some tests so I know that my preference for JavaScript doesn't completely wreck everything. Does anyone have experience writing tests for Coffee-Angular in vanilla JS?

Show Results Based on experiment_type

Posted: 28 Jun 2016 07:24 AM PDT

I have a table experiments in my database that is populated by filling out a form. One of the fields in the form is experiment_type, which is a drop down option to select between either AOV or Conversion. In my show.html.erb I'd like to display the AOV experiments and the Conversion experiments seperately. I'm kinda stuck on where to begin with this. I thought I could do something in my show action like

@aov_experiment = Experiment.where(:experiment_type => "AOV").order("created_at DESC")    @conversion_experiment = Experiment.where(:experiment_type => "Conversion").order("created_at DESC")  

Then loop through and show the results in my show.html.erb

I think I am way off here. Hoping someone can point me in the right direction.

Can I find the key an embedded document is embedded under in MongoMapper?

Posted: 28 Jun 2016 04:53 AM PDT

Say I have a document like this:

{    one: {name: "John"},    two: {name: "Paul"},    three: {name: "George"},    four: {name: "Ringo"}  }  

I've ended up with the three subdocument as a MongoMapper object. I know I can find the parent document, I can read the name attrib on the object I have, but is there an easy way to find the fact that it's embedded as three in the parent document?

I have two potential solutions, but both strike me as flaky. One is to get the class name of the object (which I'd then have to mess with since these classes are all subclasses of another class) and another would be some sort of match on all the embedded documents in the parent (which seems very non-optimal).

getting latitude and longitude values from controller in rails-geocoder gem

Posted: 28 Jun 2016 05:03 AM PDT

Is it possible to get latitude and longitude values in the controller when using geocoder gem in rails?

What am currently doing for getting all nearby location is pass the location name like below.

event_address = Event.near(location, 15, order: 'distance')  

So is there a way to fetch the lat and lng which was used for the above requested location for using later in subsequent requests for same location?

@latitude= #some method

@longitude= #some_method

Migration for changing belongs_to association

Posted: 28 Jun 2016 05:14 AM PDT

I have a model called categories currently they belong to product but I'd like them to belong to store instead. I have several thousand of these so what I'd like to do is create a migration that adds a store_id to categories and then, gets the associated product.store.id from it's current association and adds that to the store_id. After that I'd like to remove the product association.

Does anybody know how to easily and safely achieve that?

delete dash character which is at the end of the string

Posted: 28 Jun 2016 05:13 AM PDT

So I have table items in my db. I want in Item.name replace - character which is at the end of the Item.name So I try to do it like this:

 items = Item.all   items.each do |it|   it.name=it.name.gsub('/\-$/','')   it.save   end  

But it doesn't work. What do I do?

upd: I managed to do it like this:

i = Item.all   i.each do |it|   it.name=it.name.chomp('-')   it.save   end  

But still don't get why first variant didn't work

Correct s3 region not setting with paperclip

Posted: 28 Jun 2016 04:55 AM PDT

Using these two gems, I had no issues:

gem 'aws-sdk', '< 2.0'  gem "paperclip", "~> 4.3"  

When now using:

gem "paperclip", "~> 5.0.0.beta1"  gem 'aws-sdk', '>= 2.0.34'  

I have region issues in development.rb:

  config.paperclip_defaults = {         :s3_region => ENV['S3_REGION'], # us-west-2         :storage => :s3,         :s3_credentials => {         :bucket => ENV['S3_BUCKET_NAME'],         :access_key_id => ENV['AMAZON_ACCESS_KEY_ID'],         :secret_access_key => ENV['AMAZON_SECRET_ACCESS_KEY']    }  }  

I see no documentation on this. The url I'm after is https://s3-us-west-2.amazonaws.com<bucken-name>.... but I'm getting: https://s3.amazonaws.com/...

Parse Postgres date stored as string including offset timezone

Posted: 28 Jun 2016 07:07 AM PDT

I have some dates stored as strings in a postgresdb

"Fri, 24 Jun 2016 04:13:26 -0700"  

I want to treat those dates as dates.

I can use

to_timestamp(date,'Dy, DD Mon YYYY HH24:MI:SS')  

But I can't work out how to deal with the timezone. there appears to be OF as the parameter for the offset.

If I use

to_timestamp(date, 'Dy, DD Mon YYYY HH24:MI:SS OF')  

The query hangs. I can't work out what I'm doing wrong there.

Note: I'm using activerecord and rails. so the query is actually

Model.all.order("to_timestamp(date,'Dy, DD Mon YYYY HH24:MI:SS OF') DESC")  

No comments:

Post a Comment