Showing posts with label ruby-on-rails-3. Show all posts
Showing posts with label ruby-on-rails-3. Show all posts

Sunday, July 9, 2017

Slower while generating the XML from the bunch of model object

Leave a Comment
class GenericFormatter < Formatter  attr_accessor :tag_name,:objects   def generate_xml    builder = Nokogiri::XML::Builder.new do |xml|    xml.send(tag_name.pluralize) {    objects.each do |obj|         xml.send(tag_name.singularize){              self.generate_obj_row obj,xml         }                     end     }    end    builder.to_xml  end   def initialize tag_name,objects   self.tag_name = tag_name   self.objects = objects end   def generate_obj_row obj,xml    obj.attributes.except("updated_at").map do |key,value|      xml.send(key, value)    end    xml.updated_at obj.updated_at.try(:strftime,"%m/%d/%Y %H:%M:%S") if obj.attributes.key?('updated_at') end  end  

In the above code, I have implemented the formatter where I have used the nokogiri XML Builder to generate the XML by manipulating the objects passing out inside the code.It's generated the faster XML when the data is not too large if data is larger like more than 10,000 records then It's slow down the XML to generate and takes at least 50-60 seconds.

Problem: Is there any way to generate the XML faster, I have tried XML Builders on view as well but did n't work.How can I generate the XML Faster? Should the solution be an application on rails 3 and suggestions to optimized above code?

2 Answers

Answers 1

Your main problem is processing everything in one go instead of splitting your data into batches. It all requires a lot of memory, first to build all those ActiveRecord models and then to build memory representation of the whole xml document. Meta-programming is also quite expensive (I mean those send methods).

Take a look at this code:

class XmlGenerator   attr_accessor :tag_name, :ar_relation    def initialize(tag_name, ar_relation)     @ar_relation = ar_relation     @tag_name = tag_name   end    def generate_xml     singular_tag_name = tag_name.singularize     plural_tag_name = tag_name.pluralize      xml = ""     xml << "<#{plural_tag_name}>"      ar_relation.find_in_batches(batch_size: 1000) do |batch|       batch.each do |obj|         xml << "<#{singular_tag_name}>"          obj.attributes.except("updated_at").each do |key, value|           xml << "<#{key}>#{value}</#{key}>"         end          if obj.attributes.key?("updated_at")           xml << "<updated_at>#{obj.updated_at.strftime('%m/%d/%Y %H:%M:%S')}</updated_at>"         end          xml << "</#{singular_tag_name}>"       end     end      xml << "</#{tag_name.pluralize}>"     xml   end end  # example usage XmlGenerator.new("user", User.where("age < 21")).generate_xml 

Major improvements are:

  • fetching data from database in batches, you need to pass ActiveRecord collection instead of array of ActiveRecord models
  • generating xml by constructing strings, this has a risk of producing invalid xml, but it is much faster than using builder

I tested it on over 60k records. It took around 40 seconds to generate such xml document.

There is much more that can be done to improve this even further, but it all depends on your application.

Here are some ideas:

  • do not use ActiveRecord to fetch data, instead use lighter library or plain database driver
  • fetch only data that you need
  • tweak batch size
  • write generated xml directly to a file (if that is your use case) to save memory

Answers 2

The Nokogiri gem has a nice interface for creating XML from scratch, Nokogiri is a wrapper around libxml2.

Gemfile gem 'nokogiri' To generate xml simple use the Nokogiri XML Builder like this

xml = Nokogiri::XML::Builder.new { |xml|      xml.body do         xml.test1 "some string"         xml.test2 890         xml.test3 do             xml.test3_1 "some string"         end         xml.test4 "with attributes", :attribute => "some attribute"         xml.closing     end }.to_xml 

output

<?xml version="1.0"?> <body>   <test1>some string</test1>   <test2>890</test2>   <test3>     <test3_1>some string</test3_1>   </test3>   <test4 attribute="some attribute">with attributes</test4>   <closing/> </body> 

Demo: http://www.jakobbeyer.de/xml-with-nokogiri

Read More

Friday, May 5, 2017

Can't retrieve access_token, refresh_token from Omniauth authentication strategy with Devise, Rails 4

Leave a Comment

I am using such gems:

gem "omniauth-yandex" gem 'devise' 

My setup.

Routes:

 devise_for :users, :controllers => { :omniauth_callbacks => "callbacks" } 

Devise initializer:

config.omniauth :yandex, Rails.application.secrets.client_id , Rails.application.secrets.password, callback_url: "http://cb2bcdc4.ngrok.io/users/auth/yandex/callback" 

User model:

devise :database_authenticatable, :registerable,          :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:yandex]      def self.from_omniauth(auth)         where(provider: auth.provider, uid: auth.uid).first_or_create do |user|         user.provider = auth.provider         user.uid = auth.uid         user.email =  auth.info.email         user.password = Devise.friendly_token[0,20]       end    end 

CallbackController:

class CallbacksController < Devise::OmniauthCallbacksController              def yandex        #empty     end end 

View:

  <%= link_to "Sign in with Yandex", user_yandex_omniauth_authorize_path, id: "sign_in" %> 

When I click "Sign in with Yandex" my application prompts for user permission and then redirects back to my application. User is created in my database with such fields-- e-mail,provider, uid. But I would like to have also access_token, refresh_token and expires_at because I am using few Yandex API's.

When I httlog'ed above action (From clicking "Sign in .." to the redirect back to my application) I received these results:

D, [2017-04-26T19:17:42.091838 #24865] DEBUG -- : [0;30;101m[httplog] Connecting: oauth.yandex.ru:443[0m D, [2017-04-26T19:17:42.266645 #24865] DEBUG -- : [0;30;101m[httplog] Sending: POST http://oauth.yandex.ru:443/token[0m D, [2017-04-26T19:17:42.267040 #24865] DEBUG -- : [0;30;101m[httplog] Data: client_id=097253682f9f41289ec5exxxxxxx&client_secret=xxxxxxdb4fxx0eadcbb8a4143&code=xxxxx327&grant_type=authorization_code&redirect_uri=http%3A%2F%2Fcb2bcdc4.ngrok.io%2Fusers%2Fauth%2Fyandex%2Fcallback%3Fstate%xxxxxxxxxxx%26code%xxxx[0m D, [2017-04-26T19:17:42.410712 #24865] DEBUG -- : [0;30;101m[httplog] Status: 200[0m D, [2017-04-26T19:17:42.410945 #24865] DEBUG -- : [0;30;101m[httplog] Benchmark: 0.143445 seconds[0m D, [2017-04-26T19:17:42.411168 #24865] DEBUG -- : [0;30;101m[httplog] Response: {"token_type": "bearer", "access_token": "xxxxxxxxuyBwtcyAFjkBZo3F3MCiIaTI", "expires_in": 31528753, "refresh_token": "xxxxxxxxxxxClSH:Pts0u-Mfls-vdEc7-zTOod9ZWzegNFRxxxxxxxxxxxxxKHpwsqBFUHHKtg"}[0m D, [2017-04-26T19:17:42.414748 #24865] DEBUG -- : [0;30;101m[httplog] Connecting: login.yandex.ru:443[0m D, [2017-04-26T19:17:42.609376 #24865] DEBUG -- : [0;30;101m[httplog] Sending: GET http://login.yandex.ru:443/info?format=json[0m D, [2017-04-26T19:17:42.609720 #24865] DEBUG -- : [0;30;101m[httplog] Data: [0m D, [2017-04-26T19:17:42.675702 #24865] DEBUG -- : [0;30;101m[httplog] Status: 200[0m D, [2017-04-26T19:17:42.675972 #24865] DEBUG -- : [0;30;101m[httplog] Benchmark: 0.065791 seconds[0m D, [2017-04-26T19:17:42.676211 #24865] DEBUG -- : [0;30;101m[httplog] Response: {"first_name": "xxxxxxxxxxx9", "last_name": "xxxxxxxxxxxxxxx", "display_name": "xxxxx", "emails": ["xxxxxx@yandex.ru"], "default_email": "xxxxx@yandex.ru", "real_name": "xxxxxx2", "login": "xxxxxxx", "sex": "male", "id": "xxxx123"}[0m 

Question: How can I save access_token, refresh token from Omniauth authentication process to user as it is clearly visible (7th line ) that it does retrieve it using my client_id and secret without any of my code.

Thanks.

What I have tried:

Added user.access_token = auth.credentials.token to self.from_omniauth(auth) method in user model. But there wasn't any positive change.

UPDATE:

The same problem exists on different platforms. For example, on shared hosting and in Linux Ubuntu (completely fresh project from scratch).

1 Answers

Answers 1

The access token is provided by the yandex gem, or to be more specific, the omniauth-oauth2 gem.

Just get inside your controller by doing: request.env["omniauth.auth"].credentials.token

Boom. That's your access token. (refresh token and expiry data is also in the credentials hash, just print it out)

Read More

Thursday, January 19, 2017

Routes not working correctly

Leave a Comment

EDIT: Thanks for the replies, I tried everything listed below but still now luck. If I type localhosts/posts/new it takes me to the form, however the link does not work when I click from the navigation bar. I've updated the code and included my rake routes results.

I am new to ruby and working through a tutorial, however one of my links is not working and not sure what is happening.

My navigation link to create a new post is not taking me to the correct page, when I click the link to the "posts_path" the page does not change.

I can create a new posts by typing in the /posts/new in the address bar, but when I click the "New Post" link on the nav bar the page does not update (although the url displays /posts). Any idea how to fix this?

config/routes.rb

Rails.application.routes.draw do get 'sessions/new' root 'static_pages#home' get  '/search', to: 'static_pages#search' get  '/login', to: 'sessions#new' get  '/posts', to: 'posts#new', as: 'new_post' post  '/login', to: 'sessions#create' delete  '/logout', to: 'sessions#destroy' get  '/signup', to: 'users#new' get 'users/new' get 'static_pages/home' get 'posts/new' get 'sessions/new' resources :users resources :account_activations, only: [:edit] resources :password_resets, only: [:new, :create, :edit, :update] resources :posts, only: [:new, :create, :destroy] end 

app/views/layouts/_header.html.erb

<header class="navbar navbar-fixed-top navbar-inverse"> <div class="container">   <% link_to "sample app", root_path, id: "logo" %>     <nav>       <ul class="nav navbar-nav navbar-right">         <li><%= link_to "Home", root_path %></li>         <li><%= link_to "Search", search_path %></li>           <% if logged_in? %>             <li><%= link_to "Users", users_path %></li>             <li><%= link_to "Posts", posts_new_path %></li>             <li class="dropdown">              <a href='#' class="dropdown-toggle" data-toggle="dropdown">Account <b class="caret"></b></a>              <ul class="dropdown-menu">               <li><%= link_to "Profile", current_user %></li>               <li><%= link_to "Settings", edit_user_path(current_user) %></li>               <li class="divider"></li>               <li><%= link_to "Logout", logout_path, method: "delete" %></li>              </ul>            </li>            <% else %>              <li><%= link_to "Log in", login_path %></li>            <% end %>           </ul>        </nav>   </div> 

posts_controller.rb

class PostsController < ApplicationController     before_action :logged_in_user, only: [:create, :destroy]     before_action :correct_user, only: :destroy      def create             @post = current_user.posts.build(post_params)             if @post.save                     flash[:success] = "Post created!"                     redirect_to root_url             else                     @feed_items = []                     render 'static_pages/home'             end     end      def destroy             @post.destroy             flash[:success] = "Post Deleted"             redirect_to request.referrer || root_url     end     def new        @post = current_user.posts.build if logged_in?     end      private      def post_params             params.require(:post).permit(:description, :picture)     end      def correct_user             @post = current_user.posts.find_by(id:params[:id])             redirect_to root_url if @post.nil?     end end 

rake routes:

password_resets_new     GET     /password_resets/new(.:format)          password_resets#new password_resets_edit    GET     /password_resets/edit(.:format)         password_resets#edit sessions_new            GET     /sessions/new(.:format)                 sessions#new root                    GET     /                                       static_pages#home search                  GET     /search(.:format)                       static_pages#search login                   GET     /login(.:format)                        sessions#new new_post                GET     /posts(.:format)                        posts#new                         POST    /login(.:format)                        sessions#create logout                  DELETE  /logout(.:format)                       sessions#destroy signup                  GET     /signup(.:format)                       users#new users_new               GET     /users/new(.:format)                    users#new static_pages_home       GET     /static_pages/home(.:format)            static_pages#home static_pages_about      GET     /static_pages/about(.:format)           static_pages#about static_pages_search     GET     /static_pages/search(.:format)          static_pages#search posts_new               GET     /posts/new(.:format)                    posts#new                         GET     /password_resets/new(.:format)          password_resets#new                         GET     /password_resets/edit(.:format)         password_resets#edit                         GET     /sessions/new(.:format)                 sessions#new help                    GET     /help(.:format)                         static_pages#help about                   GET     /about(.:format)                        static_pages#about contact                 GET     /contact(.:format)                      static_pages#contact users                   GET     /users(.:format)                        users#index                         POST    /users(.:format)                        users#create new_user                GET     /users/new(.:format)                    users#new edit_user               GET     /users/:id/edit(.:format)               users#edit user                    GET     /users/:id(.:format)                    users#show                         PATCH   /users/:id(.:format)                    users#update                         PUT     /users/:id(.:format)                    users#update                         DELETE  /users/:id(.:format)                    users#destroy edit_account_activation GET     /account_activations/:id/edit(.:format) account_activations#edit password_resets         POST    /password_resets(.:format)              password_resets#create new_password_reset      GET     /password_resets/new(.:format)          password_resets#new edit_password_reset     GET     /password_resets/:id/edit(.:format)     password_resets#edit password_reset          PATCH   /password_resets/:id(.:format)          password_resets#update                         PUT     /password_resets/:id(.:format)          password_resets#update posts                   POST    /posts(.:format)                        posts#create                         GET     /posts/new(.:format)                    posts#new post                    DELETE  /posts/:id(.:format)                    posts#destroy 

11 Answers

Answers 1

I would suggest that you remove get 'posts/new' & get '/posts', to: 'posts#new', as: 'new_post' as these are duplicate routes.

You already have the correct route created in the route resources :posts, only: [:new, :create, :destroy]. By including new, Rails is doing this portion for you. See here: http://guides.rubyonrails.org/v4.2/routing.html#crud-verbs-and-actions

Then you should be able to use the link that everyone else has posted. <%= link_to "New Post", new_post_path %> based on the guide here: http://guides.rubyonrails.org/v4.2/routing.html#path-and-url-helpers

Answers 2

The problem is there is conflict occurring in your routes. You have defined routes twice for new

get /posts', to: 'posts#new', as: 'new_post' 

and

resources :posts, only: [:new, :create, :destroy] 

now there are 2 paths for posts#new. I suggest u remove first one. Change your html to

<li><%= link_to 'New Post', posts_path %></li> 

and it should work fine.

Answers 3

i went through your code...and this is what i recommend to add/edit changes..and sure it should work :).

  1. for routes.rb,its looks good BUT there is a duplicate url entry.So either remove get 'posts/new' or resources :posts, only: [:new, :create, :destroy] as they both will create a duplicate entry for posts#new.You can verify this by outputting your routes in seperate txt file by rake routes >> path.txt
  2. in app/views/layouts/_header.html.erb,its good too and dont need any change.
  3. in posts_controller.rb,there is a condition added for only logged in user,Kindly check if you are logged in else remove that condition and check again.
  4. Finally,debug using F12 in chrome/firefox and see what log do you get in web browser console before and after click to check is there some javascript error or not.

Answers 4

Remove get 'sessions/new' & get '/posts', to: 'posts#new', as: 'new_post'

Restart server

and try link_to "Posts", posts_new_path, method: :post

Should work

Answers 5

code for link to new post

<%= link_to "New Post", new_post_path %> 

Answers 6

Try new_post_path

Also, rake routes in terminal will list all the routes and associated helpers for you to double check against.

Finally, adding 'as' to: get '/posts', to: 'posts#new', as: 'new_post' in your routes file will allow you to define your own path name (in this case new_post_path, but you can set it as anything you'd like).

Answers 7

<%= link_to "Posts", posts_path %> corresponds to index action not to the new action. 

Remove the only condition for your posts controller in routes.rb which will create all the basic routes needed rather than specific routes.

resources :posts 

So, new_post_path returns /posts/new

Finally add a link link <%= link_to 'New Post', new_post_path %>

Answers 8

This may be helps to redirect,
in routes.rb,

resources :posts   

It gives the paths to all default controller methods like index, new, create, edit, update, show, destroy. Then check with rake routes. Get the corresponding path like,

new_post GET      /posts/new(.:format)                    posts#new   

if it correct means give the url like,

<%= link_to 'New Post', new_post_path %>
It redirects to method new in controller and render corresponding html.erb page. This url formed by the routes.rb.

OR

push the redirection url manually.In html page,

<%= button_tag "New", :onclick => "getNew()" %>    function getNew(){         var form = document.forms[0];         // get the id and value with any variable //          form.method = "post";                // pass the value to parameters //         form.var name = column name; (description r picture)          form.action = "posts/new";         form.submit();     }   

in routes.rb,

match '/posts/new' => 'posts#new', via: [:get, :post]   

It makes the manual redirection url. It calls the new in controller method.
Let me know your feedback! Thanks

Answers 9

Rails scans the routes from top to bottom i.e. routes.rb. Whenever it finds the matching routes corresponding controller#action gets executed and remaining all will be skipped(later routes after match found).

In this case routes are conflicting, So do bellow changeseverything will work fine. config/routes.rb

Rails.application.routes.draw do get 'sessions/new' root 'static_pages#home' get  '/search', to: 'static_pages#search' get  '/login', to: 'sessions#new' #get  '/posts', to: 'posts#new', as: 'new_post' #not required as resources :posts will do the job in last line post  '/login', to: 'sessions#create' delete  '/logout', to: 'sessions#destroy' get  '/signup', to: 'users#new' get 'users/new' get 'static_pages/home' get 'posts/new', to: 'posts#new', as: 'posts_new_path'  #Made changes here according to helper used in view 'posts_new_path' get 'sessions/new' resources :users resources :account_activations, only: [:edit] resources :password_resets, only: [:new, :create, :edit, :update] resources :posts, only: [:new, :create, :destroy] end  

Answers 10

As per your rake routes output the following should work

<%= link_to "New Post", posts_new_path %> 

Please let us know whether there any error comming in the console log on clicking the new post link.

Answers 11

The bottom line is that you're trying to do things in a non-Rails manner. Rails favors convention over configuration, meaning if you don't do things the Rails way, you're going to have a bad time.

This means you should clean up your routes until you have no unnecessary duplication. Right now you have 3 different routes that go to posts#new each with a different path prefix.

I'd remove:

  • get '/posts', to: 'posts#new', as: 'new_post'
  • get 'posts/new'

since resources :posts, only: [:new, :create, :destroy] already creates that route. Then your new_post_path helper should create the correct URL and your routes will have no ambiguity.

Read More

Friday, April 1, 2016

Rails: Validate uniqueness of multiple columns

Leave a Comment

Is there a rails-way way to validate that an actual record is unique and not just a column? For example, a friendship model / table should not be able to have multiple identical records like:

user_id: 10 | friend_id: 20 user_id: 10 | friend_id: 20 

3 Answers

Answers 1

You can scope a validates_uniqueness_of call as follows.

validates_uniqueness_of :user_id, :scope => :friend_id 

Answers 2

You can use validates to validate uniqueness on one attribute:

validates :user_id, uniqueness: {scope: :friend_id} 

The syntax for the validation on multiple columns is similar, but you should provide an array of fields instead:

validates :attr, uniqueness: {scope: [:attr1, ... , :attrn]} 

However, approaches that are shown above suffer from race conditions, consider the following example:

  1. database table records are supposed to be unique by n fields;

  2. multiple (two or more) concurrent requests, handled by separate processes each (application server, sidekiq or whatever you are using), try to write the same record to the table;

  3. each process in parallel validates if there is a record with the same n fields;

  4. validation for each request is passed and each process creates a record in the table with the same data.

To avoid this kind of behaviour, one should add a unique constraint to the db table. You can set it with add_index for multiple (or one) fields by running the following migration:

class AddUniqueConstraints < ActiveRecord::Migration   def change    add_index :table_name, [:field1, ... , :fieldn], unique: true   end end 

Caveat : even after you've set the unique constraint, two or more concurrent requests will try to write the same data to the db, but instead of creating duplicate records, this will result in the raise of the ActiveRecord::RecordNotUnique exception, which you should handle separately:

begin # writing to the database rescue ActiveRecord::RecordNotUnique => e # handling the case when record already exists end  

Answers 3

You probably do need actual constraints on the db, because validates suffers from race conditions.

validates_uniqueness_of :user_id, :scope => :friend_id 

When you persist a user instance, Rails will validate your model by running a SELECT query to see if any user records already exist with the provided user_id. Assuming the record proves to be valid, Rails will run the INSERT statement to persist the user. This works great if you’re running a single instance of a single process/thread web server.

In case two processes/threads are trying to create a user with the same user_id around the same time, the following situation may arise. Race condition with validates

With unique indexes on the db in place, the above situation will play out as follows. Unique indexes on db

Answer taken from this blog post - http://robots.thoughtbot.com/the-perils-of-uniqueness-validations

Read More