Thursday, August 25, 2016

Pundit authorization in index | Fixed issues

Pundit authorization in index | Fixed issues


Pundit authorization in index

Posted: 25 Aug 2016 07:34 AM PDT

I have been recently reading through the pundit gem's README and noticed that they never authorize the index view within a controller. (Instead they use scope).

They give good reasoning for this, as an index page generally contains a list of elements, by controlling the list that is generated you effectively control the data on the page. However, occasionally it may be desired to block access to even the index page itself. (Rather than allowing access to a blank index page.) My question is what would be the proper way to perform this?

I have so far come up with several possibilities, and have the following classes:

  • A model MyModel
  • A controller MyModelsController
  • A policy MyModelPolicy

In my index method of my controller, the recommended method to solve this would be as follows:

def index    @my_models = policy_Scope(MyModel)  end  

This will then allow access to the index page, but will filter the results to only what that use can see. (E.G. no results for no access.)

However to block access to the index page itself I have arrived at two different possibilities:

def index    @my_models = policy_Scope(MyModel)    authorize @my_models  end  

or

def index    @my_models = policy_Scope(MyModel)    authorize MyModel  end  

Which of these would be the correct path, or is there a different alternative that would be preferred?

Rails google analytics apis error

Posted: 25 Aug 2016 07:32 AM PDT

What does this error signify?

Missing token endpoint URI. highlighted at @account_summaries

def analytics          client = Signet::OAuth2::Client.new(access_token: session[:access_token]['access_token'])            service = Google::Apis::AnalyticsV3::AnalyticsService.new            service.authorization = client            @account_summaries = service.list_account_summaries  end  

I tried searching everywhere, but can't understand in context of Google Analytics API what does this even mean?

Technically, the code should just work, but for some reason its not playing nice. Where exactly is it going wrong?

Full code

class WelcomeController < ApplicationController        def redirect        client = Signet::OAuth2::Client.new({          client_id: 'APP ID',          client_secret: 'APP SECRET',          authorization_uri: 'https://accounts.google.com/o/oauth2/auth',          scope: Google::Apis::AnalyticsV3::AUTH_ANALYTICS_READONLY,          redirect_uri: url_for(:action => :oauth2callback)          additional_parameters: { access_type: :offline, approval_prompt: :force }        })          redirect_to client.authorization_uri.to_s      end        def oauth2callback          client = Signet::OAuth2::Client.new({          client_id: 'APP ID',          client_secret: 'APP SECRET',          token_credential_uri: 'https://accounts.google.com/o/oauth2/token',          redirect_uri: url_for(:action => :oauth2callback),          code: params[:code]        })          response = client.fetch_access_token!          session[:access_token] = response['access_token']          redirect_to url_for(:action => :analytics)        end        def analytics          client = Signet::OAuth2::Client.new(access_token: session[:access_token]['access_token'])            service = Google::Apis::AnalyticsV3::AnalyticsService.new            service.authorization = client            @account_summaries = service.list_account_summaries      end    end  

parse json from rails 5 rest api to android app without models

Posted: 25 Aug 2016 07:23 AM PDT

i am new to rails 5 and i stuck on how to parse JSON data which will be retrieved from wikipedia api without storing in rails database. is there any gem for wikipedia because i got most of gems are obsolete.

Rails App with Devise Based Authentication on Multiple Servers - Sign in issue

Posted: 25 Aug 2016 07:32 AM PDT

I am using the Devise Gem for authentication in my Rails app and it works fine. So far we only had one server hosting the Rails application.

Now with AWS migration, we have two servers hosting the application. The sign in process has broken and we cannot log in. If we remove one server from the Load Balancer, it starts working again. Adding the server back breaks the login system.

We use ActiveRecord based authentication in a master-master configuration, viz. There are two DB servers in master-master mode that remain in sync.

How to add true a "partial" in js code? I wrote a js code in file "create.js.erb" but it don't work

Posted: 25 Aug 2016 07:00 AM PDT

I want to render 'partial' that when I create new micropost

My controller :

  def create      @micropost = current_user.microposts.build(micropost_params)      if @micropost.save        flash[:success] = "Micropost created!"        #redirect_to root_url        respond_to do |format|          format.html { redirect_to root_url }          format.js        end      else        @feed_items = []        render 'static_pages/home'      end    end  

I created file "create.js.erb":

$('.microposts').prepend("<%=j render 'shared/feed' %>");  

I want to render "render 'shared/feed'" in file "static_pages/home.html.erb":

<% if signed_in? %>      <div class="row">        <aside class="col-md-5 col-md-offset-0">          <section>            <%= render 'shared/user_info' %>          </section>          <section>            <%= render 'shared/stats' %>          </section>          <section>            <%= render 'shared/micropost_form' %>          </section>        </aside>        <div class="col-md-offset-5" id="microsoft_feed">          <h3>Micropost Feed</h3>          <%= render 'shared/feed' %>        </div>      </div>  <% else %>      <div class="center hero-unit">        <h1>Welcome to the Sample App</h1>          <h2>          This is the home page for the          <a href="http://railstutorial.org/">Ruby on Rails Tutorial</a>          sample application.        </h2>          <%= link_to "Sign up now!", signup_path, class: "btn btn-large btn-primary" %>      </div>        <%= link_to image_tag("ruby_on_rails.png", alt: "Rails"), 'http://rubyonrails.org/' %>  <% end %>  

_feed.html.erb :

<% if @feed_items.any? %>  <ol class="microposts">    <%= render partial: 'shared/feed_item', collection: @feed_items %>  </ol>  <%= will_paginate @feed_items %>  

_feed_item.html.erb :

<li id="<%= feed_item.id %>">    <%= link_to gravatar_for(feed_item.user), feed_item.user %>    <span class="user">      <%= link_to feed_item.user.name, feed_item.user %>    </span>    <span class="content"><%= feed_item.content %></span>    <span class="timestamp">      Posted <%= time_ago_in_words(feed_item.created_at) %> ago.    </span>    <% if current_user?(feed_item.user) %>        <%= link_to "delete", feed_item, method: :delete, remote: true,                    data: { confirm: "You sure?" },                    title: feed_item.content %>    <% end %>  </li>  

My git with project : https://github.com/py4ina/twitter

How to run delayed jobs in production in Rails 4.2 without running rake jobs command?

Posted: 25 Aug 2016 07:20 AM PDT

In development mode, we use rake jobs:work. In the same way, inorder to test in the production mode, we use RAILS_ENV=production rake jobs:work. As entire my application is on Apache Nginx server, is there any option like any gem / code that runs background and how it is used to run the jobs without running this command?

How to test catching StandardError in Rails controller

Posted: 25 Aug 2016 06:48 AM PDT

I have a root controller in my rails api application something like:

   # app/controllers/api_controller.rb     class ApiController < ApplicationController         rescue_from StandardError, with: :handle_standard_error           ##         # For catching all unhandled errors that might be thrown         ##         def handle_standard_error(exc)           # don't squash in test mode           raise exc if ENV['RAILS_ENV'] == 'test'             msg =              if ENV['RAILS_ENV'] == 'production'               I18n.t('unhandled_error_occurred')             else               exc.message             end             render 'error', :internal_server_error         end     end  

Essentially, this doesn't handle the exception in test mode, outputs a generic message in production and outputs the actual exception in development.

I'd like to be able to test the behaviour, with something like:

    # test/controllers/api_controller_test.rb      test 'handle standard error' do        ENV['RAILS_ENV'] = 'production'        # call a function to throw an unexpected exception        assert_equal expected_prod, response.body          ENV['RAILS_ENV'] = 'development'        # call said function again        assert_equal expected_dev, response.body          ENV['RAILS_ENV'] = 'test'        assert_raises(StandardError) do          # call said function a third time        end      end  

My problem is that to test the function I have to deliberately leave a method and route in my code just for testing the error which seems a bit backwards.

Does anyone have ideas on how to test the error handling, or a way to manage it better?

How to handle 300 Multiple Choices Exception for Rails

Posted: 25 Aug 2016 06:31 AM PDT

I have an exception error for testing an API that I am not quite sure how to handle. Here is the snippet of code at the bottom.

begin    open(release_url(uuid)) do |feed|        response = JSON.parse(feed.read)        return get_target_releases_json(response['targets']) if feed.status.first != 200        return if pss.etag == feed.meta['etag']        response['releases']      end    rescue Exception => e      puts "#---Exception---#"      puts e  end  

What is pertinent to understand the problem is the open(url) method.

When I reach this point using byebug I get an exception that is a 300 - Multiple Choices error. I read a little bit about it but I don't understand what I need to do to correct this. The api (which is internal to my company btw) is supposed to return a JSON structure when it hits 300. When I place this api url in my browser, I am able to see the JSON payload but when I try to use it programmatically, it errors out. Where does the problem lie? Is it in the api url or could it be elsewhere? As or right now, I can't do anything with this test url call so I'm a little bit stuck. Does anyone have any ideas to discover what I can do with this?

undefined class/module Delayed jobs Rails 4.2

Posted: 25 Aug 2016 06:17 AM PDT

I migrated my Rails app from 3.2 to 4.2.6. In this there is a view where we are listing all the jobs which are not running and the jobs that are in queue. This view is showing the error as follows:

ArgumentError - undefined class/module Report:
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/class_loader.rb:54:in resolve'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/class_loader.rb:46:in
find'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/class_loader.rb:28:in load'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/to_ruby.rb:396:in
resolve_class'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/to_ruby.rb:208:in visit_Psych_Nodes_Mapping'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/visitor.rb:16:in
visit'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/visitor.rb:6:in accept'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/to_ruby.rb:32:in
accept'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/to_ruby.rb:330:in block in register_empty'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/to_ruby.rb:330:in
register_empty'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/to_ruby.rb:141:in visit_Psych_Nodes_Sequence'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/visitor.rb:16:in
visit'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/visitor.rb:6:in accept'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/to_ruby.rb:32:in
accept'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/to_ruby.rb:338:in block in revive_hash'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/to_ruby.rb:336:in
revive_hash'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/to_ruby.rb:374:in revive'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/to_ruby.rb:208:in
visit_Psych_Nodes_Mapping'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/visitor.rb:16:in visit'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/visitor.rb:6:in
accept'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/to_ruby.rb:32:in accept'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/to_ruby.rb:311:in
visit_Psych_Nodes_Document'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/visitor.rb:16:in visit'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/visitor.rb:6:in
accept'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/visitors/to_ruby.rb:32:in accept'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych/nodes/node.rb:38:in
to_ruby'
/home/abcuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/psych.rb:253:in load' app/views/admin/_jobs_table.html.erb:16:inblock in _app_views_admin__jobs_table_html_erb__1370250790448890911_86041620'

my controller:

  def jobs      if request.get?        @jobs = Delayed::Job.order('created_at desc').all      elsif params[:id]        @job = Delayed::Job.destroy(params[:id])          respond_to do |format|          format.html { redirect_to admin_jobs_path }        end      end    end  

In admin/jobs.html.erb, I am rendering _jobs_table.html.erb as:

<table class="jobs">      <tr>          <th>Id</th>          <th>Priority</th>          <th>Attempts</th>          <th>Object</th>          <th>Method</th>          <th>Locked by</th>          <th>Created</th>          <th>Error</th>      </tr>      <% reset_cycle("rows") %>      <% if @jobs %>          <% @jobs.each do |item| %>              <% obj = YAML.load(item.handler) %>              <tr class="<%= cycle("even", "odd", :name => "rows") %>" id="job_item_<%= item[:id] %>">                  <td align="right" width="5%"><%= item[:id] %></td>                  <td align="right" width="5%"><%= item[:priority] %></td>                  <td align="right" width="5%"><%= item[:attempts] %></td>                  <td align="left"><%= "#{obj.object.class}:#{obj.object.id}" rescue nil %></td>                  <td align="left"><%= obj.method_name %></td>                  <td align="left"><%= item[:locked_by] %></td>                  <td align="left"><%= item[:created_at].in_time_zone.strftime('%a %b %d, %I:%M%p %Z') %></td>                  <td align="left"><%= item[:last_error] %></td>              </tr>          <% end %>      <% end %>  </table>  

The error is shown at YAML.load line in the above code.

Please help.

Customize the validation when user sign in in devise

Posted: 25 Aug 2016 06:21 AM PDT

Honestly i know how to change error messages of devise through devise.en.yml

I have a website that uses Devise for authentication.

While sign in if email and password is empty it give me error

Invalid email or password.

but I want to show different error messages for users for different cases:

Like , if email field is empty and password is present than show

Email can't be blank.

else if password field is empty and email is present than show

Password can't be blank.

else password and email are unauthenticated than show

invalid email or password

which currently working.

i dont want to remove :validatable from my modal.

i tired validates :email, :presence => true, :email => true

from here

but when i sign up it show 2 errors of

Email can't be blank.

one error of devise and other for modal..

please tell me how to do this validation only for user sign in .

Thank you in advance. :)

Rails link_to remote true issue when with browser history

Posted: 25 Aug 2016 07:32 AM PDT

I'm using the following code to get data via JS request on my search page

<%= link_to 'All', '/search?type=all', id: 'active', remote: true %>  <%= link_to 'Photographers', '/search?type=photographers', remote: true %>  

It's all working fine and I'm getting data as expected. But when I click some other link and then hit back button (provided by browser) it's showing me the JS request data on a blank page instead of going back to search page.

Is there any workaround or fix to this?

in routes.rb

resources :search, only: [:index]  

in search controller

def index    // search processing      respond_to do |format|      format.html      format.js    end  end  

search/index.js.erb

$('#search-area').html("<%= j render partial: 'search_area' %>");  

I'm using Rails 5.0 with Puma

ActionView::Template::Error (undefined method `full_name' for nil:NilClass ) [on hold]

Posted: 25 Aug 2016 06:34 AM PDT

I am adding a new role in my role table, the role is successfully added and it's working properly. In the view automatically hr folder created (I add two new page _internal_employee_page.html.erb, _employee_details.html.erb) I have created one controller hr_controller.rb

_internal_employee_page.html.erb

    <div class="client-dash-page head-border matching-profile recrut-dashboard">          <div id="job_details">              <%= render "hr/employee_details" %>          </div>      </div>  </div>  

_employee_details.html.erb

<div class="panel-group" id="client-dash-accordion" role="tablist" aria-multiselectable="true">  <div class="panel">  <h3> Employee Name : <%= @employees.full_name %> </h3>     <a role="button" data-toggle="collapse" data-parent="#client-dash-accordion" href="#client-collapse1" aria-expanded="true" aria-controls="client-collapse1" class="panel-title-arrow"> </a>            </h4>  </div>     

HrController

class HrController < ApplicationController      def internal_employee_page      @employees = OfferLetter.all            end      def employee_details        @employees = OfferLetter.all    end    end  

user_hr.rb

class UserHr < User    attr_accessor :full_name    has_many :offer_letter  end  

offer_letter.rb

class OfferLetter < ActiveRecord::Base    belongs_to :user_hr  end  

routes.rb

Recruitment::Application.routes.draw do    get 'hr/internal_employee_page' => 'hr#internal_employee_page', as: :internal_employee_page  end  

The error is here

<h3> Employee Name : <%= @employees.full_name %> </h3>  

full_name is a column name, I want to print the value of full_name column. Please help me I have tried so many times but I am not able to solve this problem.

SQLite db encrypted upon creation

Posted: 25 Aug 2016 05:37 AM PDT

Trying to open recently created SQLite database in 'DB Browser for SQLite' app and it's asking me to enter the key used to encrypt the database. I just created the DB on command line for a Rails tutorial. No encryption knowingly made. I tried all the keys I can find - anybody know where this key may be? Tried usual default passwords too.

DB Browser SQLCipher encryption alert

Rails ransack gem search with multiple related records

Posted: 25 Aug 2016 05:25 AM PDT

I have a users table and skills table, user has many skills through a middle table skills_users, i want to search all users who have both SKILL_A and SKILL_B but dont know how can i do this using ransack gem, i have read ransack documentation but of no use.

How to redirect to a subdomain using lvh

Posted: 25 Aug 2016 05:23 AM PDT

I have the url like this orgname.lvh.me:3000 it's working fine, and well. Now I need to redirect to this url after a specific action. How do I do this

I have tried this

 root_path(subdomain: "orgname")   

But this is simply going to localhost:3000. But instead I want to redirect to the url like

orgname.lvh.me:3000  

trying to install ruby gem json in cygwin

Posted: 25 Aug 2016 05:41 AM PDT

I am using cygwin on windows 7 with ruby package installed.

$ruby -v ruby 2.2.5p319 (2016-04-26 revision 54774) [i386-cygwin]

when i run the following command gem install json all other packeges i've installed work fine except json..

$ gem install json  Building native extensions.  This could take a while...  ERROR:  Error installing json:          ERROR: Failed to build gem native extension.        current directory: /home/firstname_lastname/.gem/ruby/gems/json-2.0.2/ext/json/ext/generator  /usr/bin/ruby.exe -r ./siteconf20160825-17572-1vtybn6.rb extconf.rb  creating Makefile    current directory: /home/firstname_lastname/.gem/ruby/gems/json-2.0.2/ext/json/ext/generator  make "DESTDIR=" clean  rm -f  rm -f generator.so  *.o  *.bak mkmf.log .*.time    current directory: /home/firstname_lastname/.gem/ruby/gems/json-2.0.2/ext/json/ext/generator  make "DESTDIR="  gcc -I. -I/usr/include/ruby-2.2.0 -I/usr/include/ruby-2.2.0/ruby/backward -I/usr/include/ruby-2.2.0 -I. -DJSON_GENERATOR     -ggdb -O2 -pipe -Wimplicit-function-declaration    -o generator.o -c generator.c  In file included from generator.c:1:0:  ../fbuffer/fbuffer.h:5:18: fatal error: ruby.h: No such file or directory   #include "ruby.h"                    ^  compilation terminated.  make: *** [Makefile:239: generator.o] Error 1    make failed, exit code 2    Gem files will remain installed in /home/firstname_lastname/.gem/ruby/gems/json-2.0.2 for inspection.  Results logged to /home/firstname_lastname/.gem/ruby/extensions/x86-cygwin/json-2.0.2/gem_make.out  

I've looked far and wide for a solution but have hit a brick wall.

Appreciate some assistance! thank you.

Facebook Web SDK for login Resize

Posted: 25 Aug 2016 04:50 AM PDT

I have used Facebook WEB SDK for LOGIN in ROR web application, login popup is what i am getting is in small size, so from background i can use the app without login to facebook, I want to change the width and height of popup so that it should restrict the app from background?Does any know about it, please let me know.

Rails no 'Access-Control-Allow-Origin' header issue with unhandled socket.io url

Posted: 25 Aug 2016 05:56 AM PDT

I am testing out a webrtc demo for rails, but am having terrible connectivity issues. I have tried multiple things online but cannot crack this, it might be a simple mistake or a fundamental misunderstanding, but what I have done is this:

webrtc-rails using NodeJS and socket.io

I am using localhost:3000 for the home url of the page but am trying to connect from client to server via localhost:2013. I have two error messages at the moment:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.  

and

info  - unhandled socket.io url   (when  running node server.js)  

My set up is this:

server.js

var http = require('http');  var app = http.createServer(function (req, res) {  }).listen(2013);  

client.js

var socket = io.connect('localhost:2013');    socket.on("created", function (){    console.log("On Created");    isInitiator = true;    console.log('isInitiator', isInitiator);  })  

application.rb

config.middleware.insert_before 0, Rack::Cors do    allow do      origins '*'      resource '*', :headers => :any, :methods => [:get, :post, :options]    end  end  

config.ru

require 'rack/cors'    use Rack::Cors do      allow do      origins '*'      resource '*',          :headers => :any,          :methods => [:get, :post, :delete, :put, :options, :patch]    end    end  

I have updated all my gems and socket.io. I keep wondering whether there is a problem finding socket.io as if I navigate to page localhost:3000/socket.io/socket.io.js, there is nothing there as I would expect... I have also tried adding the CORS headers into the application rb rile without the middleware/rack gem, but it makes no difference. Any help much appreciated.

Shopify API call from App Proxy Controller

Posted: 25 Aug 2016 06:35 AM PDT

I need to make an API call from the Proxy App Controller. I know I need to retrieve my Session from Database after the User has Installed the APP, but I don't know how to do it?

I have a Rails / Heroku APP.

Thanks, CR

AWS Elastic Beanstalk and Github with same .gitignore

Posted: 25 Aug 2016 05:54 AM PDT

I m using github for hosting my code and AWS Elastic Beanstalk to deploy my project. There is no any relation between them while deploying.

So I have too big compiled bundle.js files. Its automatically compiles in any code changes. Because of that we are getting too many conflicts with my team.

I have disabled them from .gitignore but when I deployed with: eb deploy ElasticBeanstalk doesn't track the bunle.js files as well.

So I'd like to ignore my files only for github but they should be tracked when I use eb deploy.

Is there any solution for this case. Thanks

How to avoid a UX freelancer to access my rails application model and controller code?

Posted: 25 Aug 2016 04:38 AM PDT

I have an web application in Rails 4 and its front end deserves a thoroughly review. I was thinking about using a remote freelancer to do that, but the risk of intellectual property leak is very high. Is there any way to hide the controller and model code from UX freelancer, but still give him support to test its changes on the erb/css/js on the real application?

Rails Capistrano App - Environment Variables getting changed in application

Posted: 25 Aug 2016 04:35 AM PDT

Tech Stack : Rails, Capistrano and Phusion Passenger App with Nginx, Ubuntu 14.04

The ENV['PATH'] variable is showing different values when querying it through Rails Console and when application is running.

e.g. In Rails Console, the value is: /usr/local/sbin:/usr/bin While when running application, it is showing : /usr/local/ruby/1.9.1/bin

This is causing OS level operations to fail while running application.

How to achieve Zero down time deployment using Chef?

Posted: 25 Aug 2016 07:42 AM PDT

I am looking for a zero downtime deployment chef recipe where I can deploy my java/ROR application on my server with out down time ?

Please suggest me the steps to follow to achieve Zero down time deployment both in java & ROR enviroment with examples ?

Displaying tiff image in google maps

Posted: 25 Aug 2016 05:47 AM PDT

I'm using Google maps and I want to display some portion of the image(tiff image) on the map based on conditions.Image should overlay on maps.

Example

In displaying the temperature of some area of japan, when I select a year, based on that year particular area of the image should overlay on the map.

How I can upload the tiff image on maps and uploaded image must overlay on the correct place. Any help would be appreciable.

Rails. Cache a part of JSON responce

Posted: 25 Aug 2016 04:03 AM PDT

The action is responses with large JSON object, which can be separated into dynamic and static parts.

 render :json => {:dynamic => someting, :static => huge_static_object}  

Evaluation of static part take too long, so it cached.

 huge_static_object = Rails.cache.fetch(key) do     do_something   end     render :json => {:dynamic => something, :static => huge_static_object}  

Now rails deserialization one each reading from cache + serialization to JSON. So let's store results at the cache as JSON.

huge_static_object = Rails.cache.fetch(key) do     do_something.to_json   end     render :json => {:dynamic => something, :static => huge_static_object}  

Now we have a problem with serialization on render because dynamic part need to be serialized, but static part is already serialized string. So add a simple proxy class.

class JsonStringProxy      def initialize arg      @object = arg    end      def to_json(*args)      self    end      def as_json(*args)      self    end      def encode_json(*args)      @object    end  end     huge_static_object = Rails.cache.fetch(key) do     do_something.to_json   end     render :json => {:dynamic => something, :static => JsonStringProxy.now(huge_static_object)}  

Now all work well, but may be any more easy way to do same?

How to map guard-rspec to multiple different files?

Posted: 25 Aug 2016 07:01 AM PDT

Say I have a controller in app/controllers

I have a series of request specs, one for each action in controller. How do I tell guard when watching a controller, to not only run spec/controllers/controller_spec.rb file but also run:

  • spec/requests/controller/index_spec

  • spec/requests/controller/create_spec

  • spec/requests/controller/update_spec

  • spec/requests/controller/delete_spec

  • spec/requests/controller/show_spec

?

Rails transaction in delayed job

Posted: 25 Aug 2016 03:39 AM PDT

Model (Item)    def save_item      self.items         // Here doing some calculation and some process      end    end    Controller    def item      Item.delay.save_item     end  

Here i have one model and one controller, here the problem comes when i am calling this save_item function through delay and if anything fails in that save_item function i don't want to do any of the transactions, so is there any way to accomplish with this rails "transaction concept" because once the worker failed after sometimes it will run again

Removing duplicates from search results when searching two data types

Posted: 25 Aug 2016 03:43 AM PDT

In my Ruby on Rails app, I have a page that displays search results. The search covers people and households.

When people are displayed in the search results, their household is also displayed. If a search matches a household's address but the household is already shown in the results against a person, I only want to display the person (meaning the household is displayed once, not twice).

In Ruby, how would I compare @results.households and @results.people arrays and display a list of results in ERB that removes a household.id from the list if it matches a person.household.id that is also included in the results.

The simplified data model is as follows:

Household

  • ID
  • Address
  • People
    • ID
    • Name

Person

  • ID
  • Household
    • ID
    • Address

Prevent deletes from joined table with has_many :through

Posted: 25 Aug 2016 03:07 AM PDT

There are such models:

class Event < ActiveRecord::Base    has_many :event_categories    has_many :categories, through: :event_categories      validates_presence_of :categories  end    class EventCategory < ActiveRecord::Base    belongs_to :event    belongs_to :category      validates_presence_of :event, :category  end    class Category < ActiveRecord::Base     has_many :event_categories     has_many :events, through: :event_categories  end  

When assigning event.categories = [] it immediately deletes corresponding rows from event_categories and event becomes invalid. How to prevent such a behavior in Rails 4.2.1? I expect it is adding error like Categories could not be empty and not deleting from event_categories.

searchkick search HABTM

Posted: 25 Aug 2016 06:44 AM PDT

How can I use https://github.com/ankane/searchkick to search both Users and Skills and return users with skills searched for. Most relevant result should reflect how many of the skills the User has.

My Models look like this:

class User < ApplicationRecord      searchkick      has_many :user_skills      has_many :skills, through: :user_skills  end    class Skill < ApplicationRecord      searchkick      has_many :user_skills      has_many :users, through: :user_skills  end    class UserSkill < ApplicationRecord      searchkick      belongs_to :user      belongs_to :skill  end  

I have tried the following, but no result are returned:

@search = User.search "*", where: {      skill_ids: {all: [1, 3]}    }  

No comments:

Post a Comment