Thursday, 13 March 2014

Compare CarrierWave ,Paperclip and Dragonfly in rails

 (reference :  
http://cloudinary.com/blog/ruby_on_rails_image_uploads_with_carrierwave_and_cloudinary,http://stackoverflow.com/questions/7419731/rails-3-paperclip-vs-carrierwave-vs-dragonfly-vs-attachment-fu.etc)
Attachment_fu 
 Rick Olsen programmed the best attachment plugin for Ruby on Rails — attachment_fu. It manages the server side upload process, storage, and retrieval of almost any attachment. For photographs it manages resizing and thumbnails, too. Storage options include saving to the filesystem, saving attachments into the database, or saving onto the Amazon S3 storage network. 
Attachment_fu for rails-3.2 and later..  
 https://rubygems.org/gems/pothoven-attachment_fu 
Dragonfly  
 1.Dragonfly is a highly customizable ruby gem for handling images and other attachments and is already in use on thousands of websites.  
 2.The impressive thing about Dragonfly, the thing that separates it from most other image processing plugins, is that it allows on-the-fly resizing from the view.    
3.Not needing to configure thumbnail sizing or other actions in a  separate file is a huge time and frustration saver. It makes Rails view code likeimage_tag @product.image.thumb('150x150#') possible. 
4.The magic is all made possible by caching. Instead of building the processed version on upload and then linking to individual versions of  the image, the plugin generates images as they are requested. While this is a problem for the first load, the newly created image is http cached for all subsequent loads, by default using Rack::Cache, though other more robust solutions are available should scaling become an issue.

Advantage :  
   1.Will I be changing image size often? Example: if you want to let your users change the size of their pictures (or your need flexibility in size for some other reason), or really fast development.  
   2.Yes: Dragonfly  
   3.No: either Carrierwave or Paperclip   
   4.can be used it with mongomapper with no trouble, but Carrierwave have dropped support for monog mapper.  
   5.As long as cache-proxy in front, it's fine with Dragonfly.  
   6.Should work with mongomapper, as it only extends ActiveModel  
   7.Generates thumbs on the fly (easier to create new layouts/thumbsizes)  
   8.Only one file stored! Saves space :)  
   9.Dragonfly does processing on the fly, i.e. (is meant to be used behind a cache-proxy such as Varnish, Squid or Rack::Cache, so that while the first request may take some time, subsequent requests should be super-quick!) 
 Disadvantage :  
   1.Eats CPU on every request if you don't have a cache-proxy, rack::cache or similar.  
   2.No way to access thumbs as files if needed.  
  
CarrierWave  
 This gem provides a simple and extremely flexible way to upload files from Ruby applications. It works well with Rack based web applications, such as Ruby on Rails.  
  
CarrierWave advantage  
   1.Simple Model entity integration. Adding a single string ‘image’ attribute for referencing the uploaded image.  
   2."Magic" model methods for uploading and remotely fetching images.  
   3.HTML file upload integration using a standard file tag and another hidden tag for maintaining the already uploaded "cached" version.  
   4.Straight-forward interface for creating derived image versions with different dimensions and formats. Image processing tools are nicely hidden behind the scenes.  
   5.Model methods for getting the public URLs of the images and their resized versions for HTML embedding.  
   6.if built-in rails caching, Carrierwave will perform better, as the files can be loaded without any processing. If you don't do any processing, it doesn't matter.  
   7.Generates thumbs on upload (saves CPU time)  
   8.Can use files directly from a static/cached document  
   9.Doesn't need any cache-front  
   10.Supports various storage backends (S3, Cloudfiles, GridFS, normal files) easy to extend to new storage types if needed.  
  
One of the fact that it doesn't clutter your models with configuration. You can define uploader classes instead. It allows you to easily reuse, extend etc your upload configuration.  
What we liked most is the fact the CarrierWave is very modular. You can easily switch your storage engine between a local file system, Cloud-based AWS S3, and more. You can switch the image processing module between RMagick, MiniMagick and other tools. You can also use local file system in your dev env and switch to S3 storage in the production system. 
Carrierwave has good support for exterior things such as DataMapper, Mongoid, Sequel and even can be used with a 3rd party image managment such as cloudinary The solution seems most complete with support coverage for about anything, but the solution is also much messier (for me at least) since there is a lot more code that you need to handle. 
Need to appreciate the modular approach that CarrierWave takes. It’s agnostic as to which of the popular S3 clients you use, supporting both aws/s3 and right_aws. It’s also ORM agnostic and not tightly coupled to Active Record. The tight coupling of Paperclip has caused us some grief at work.  
 
CarrierWave disadvantage  
   1.You can't validate file size. There is a wiki article that explains how to do it, but it does not work.  
   2.Integrity validations do not work when using MiniMagick (very convenient if you are concerned about RAM usage). You can upload a corrupted image file and CarrierWave will throw an error at first, but the next time will swallow it.  
   3.You can't delete the original file. You can instead resize it, compress, etc. There is a wiki article explaining how to do it, but again it does not work.  
   4.It depends on external libraries such as RMagick or MiniMagick. Paperclip works directly with the convert command line (ImageMagick). So, if you have problems with Minimagick (I had), you will lose hours diving in Google searches. Both RMagick and Minimagick are abandoned at the time of this writing (I contacted the author of Minimagic, no response).  
   5.It needs some configuration files. This is seen as an advantage, but I don't like having single configuration files around my project just for one gem. Configuration in the model seems more natural to me. This is a matter of personal taste anyway.  
   6.If you find some bug and report it, the dev team is really absent and busy. They will tell you to fix bugs yourself. It seems like a personal project that is improved in spare time. For me it's not valid for a professional project with deadlines.  
   7.Doesn't natively support mongomapper  
   8.Uses storagespace for every file/thumb generated. If you use normal file storage, you might run out of inodes!  
 
Paper_Clip  
 Paperclip is intended as an easy file attachment library for Active Record. The intent behind it was to keep setup as easy as possible and to treat files as much like other attributes as possible. This means they aren't saved to their final locations on disk, nor are they deleted if set to nil, until ActiveRecord::Base#save is called. It manages validations based on size and presence, if required. It can transform its assigned image into thumbnails if needed, and the prerequisites are as simple as installing ImageMagick (which, for most modern Unix-based systems, is as easy as installing the right packages). Attached files are saved to the filesystem and referenced in the browser by an easily understandable specification, which has sensible and useful defaults. 
Advantage :  
 1.validations, Paperclip introduces several validators to validate your attachment:  
   AttachmentContentTypeValidator  
   AttachmentPresenceValidator  
   AttachmentSizeValidator  
 2.Deleting an Attachment  
 Set the attribute to nil and save.  
 @user.avatar = nil @user.save  
 3.Paperclip is better for an organic Rails environment using activerecord and not all the other alternatives. Paperclip is much easier to handle for beginning rails developers and it also has advanced capabilities for the advanced developer.  
 4. A huge fan of Paperclip because it doesn't require RMagick, it's very easy to set it up to post through to Amazon S3 and declaring everything in the models (validations, etc) keeps things clean.  
 5.With respect to multiple file uploads and progress feedback, both are possible with both Paperclip and Attachment_fu, but both typically require some elbow grease with iframes and Apache to get working.  
 
Migrating From Paperclip to Carrierwave  
 (http://bessey.io/blog/2013/04/07/migrating-from-paperclip-to-carrierwave/)  

Wednesday, 5 March 2014

Ruby on Rails: How to pass variable between controllers

  way 1:   
  class BarsController < UsersController   
  before_filter :init_foo_list   
  def method1   
   render :controller => "FoosController", :action => "method2"   
  end    
  def init_foo_list   
   params[:shared_param__] ||= ['Money', 'Animals', 'Ummagumma']   
  end    
  end   
  class FoosController < UsersController   
  def method2   
   params[:shared_param__].each do | item|   
   # do something   
   end   
  end   
  end   

Ruby on Rails: How to pass variable between controller actions

 way 1 :  
        Global variable  
        (fail during concurrent requests)  
 way 2:  
        class variable  
        (fail during concurrent requests)  
 way 3 :  
 * Stash the object on the server between requests. The typical way is to save it in the session, since it automatically serializes/deserializes the object for you.  
 * Serialize the object and include it in the form somewhere, and  
 deserialize it from the parameters in the next request.  
 so you can store attributes in the session.  
 def first  
  @item = Item.new(params[:item])  
  session[:item_attributes] = @item.attributes  
 end  
 def second  
  @item = Item.new(session[:item_attributes])  
  @item.attributes = params[:item]  
 end  
 way 4 :  
        The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed to the very next action and then cleared out.  
 def new  
   @test_suite_run = TestSuiteRun.new  
   @tests = Test.find(:all, :conditions => { :test_suite_id => params[:number] })  
   flash[:someval] = params[:number]  
 end  
 def create      
   @test_suite_run = TestSuiteRun.new(params[:test_suite_run])  
   @tests = Test.find(:all, :conditions => { :test_suite_id => flash[:someval] })    
 end  
 way 5:  
 you can use rails cache.  
 Rails.cache.write("list",[1,2,3])  
 Rails.cache.read("list")  
 But what happens when different sessions have different values?  
 Unless you ensure the uniqueness of the list name across the session this solution will fail during concurrent requests  
 way 6:  
 In one action store the value in db table based on the session id and other action can retrieve it from db based on session id.  
 way 7:   
 class BarsController < UsersController  
  before_filter :init_foo_list  
  def method1  
   render :method2  
  end   
  def method2  
   @foo_list.each do | item|  
    # do something  
   end  
  end  
  def init_foo_list  
   @foo_list ||= ['Money', 'Animals', 'Ummagumma']  
  end  
 end  
 way 8:   
 From action sent to view and again from view sent to other actions in controller.  

Saturday, 22 February 2014

part :1 Scrum Introduction

 Introduction 
 
 1.Scrum is framework for product development. 
 2.Scrum is framework for learning about work and process we used to do it. 
 
 Individuals and Interactions over processes and tools  
 Working Software over comprehensive documentation  
 Customer collaboration over contract negotiation  
 Responding to change over following a plan 
 
not a scrum   
             Requirement analysis  Design Code Integration  Test   Deploy   
 jan               *  
 feb               *  
 march                                  *  
 april                                     *  
  may                                           *  
  june                                           *  
  july                                                     *  
 aug                                                     *  
 sep                                                                 *    
 oct                                                                 *  
 nev                                                                          *  
 dec                                                                           * 
 
 Scrum  
               Requirement analysis  Design Code Integration  Test   Deploy   
 sprint 1              *                     *      *         *           *       * (shippable product)  
 sprint 2              *                     *      *         *           *       * (shippable product)  
 sprint 3              *                     *      *         *           *       * (shippable product)  
 .  
 .  
 etc 
 a.At the end of sprint product should be shippable.  
  
Scrum elements  
  
 Roles  
 Artifacts  
 Meetings   
 
Roles: 
a.Product Owner  
   i.Responsible for Return on investment  
   ii.Final arbiter of requirement questions  
   iii.focused more on what than on how 
b.Scrum Development Team  
   i.Cross-functional group  
   ii. Attempts to build a potentially shippable product increment" every sprint.  
   iii.Collaborates  
   iv.self-organizing .  
 Scrum development team size 4-9 people 
c. Scrum Master  
 a.has no management authority  
 b.Does not have project manager role  
 c.facilitator  
 scrum master protect team from destraction and interruption.Teaches how to use scrum and promotes  
 best engineering practices.scrum master Enforces timeboxes. 
Artifacts 
 
 Product backlog  
 Sprint backlog 
 
 Product backlog:  
 List of customer centric features are priorities by product owner.List of everything we might do,  
 if not in backlog it doesnot exist. Any one can add item to product backlog but it is priorities  
 by product owner and made visible by scrum master.  
                           high priority  low priority  
 product backlog item  
 product backlog item  
 product backlog item  
 product backlog item  
 product backlog item 
Sprint backlog : 
 What we have agreed to do during current sprint
 commited backlog       not started     in progress      completed  
 items 
product backlog item       task            task             task  
 pbi  
 pbi 
        what                               how 
Meetings in scrum  
 Four meetings in scrum 
 1.sprint planning meeting  
     |  
 2.daily scrum(daily, throughtout scrum)  
     |  
 3.sprint review meeting  
     |  
 4.spring retrospective meeting  
     |  
 not official name but  
 5.Backlog refinement meeting   
Two week plan  
               m          t w t f | m t            w            t               f  
 9am        <------------daily stand up meeting--------------------------------------->  
             sprint                                                       sprint review  
         planning meeting                                               meeting (2 hours)  
            (4 hours)  
 1pm  
                                          backlog refinement           sprint retrospective  
                                           meeting (2 hours)              meeting (2 hours)  
 5pm 
1.sprint planning meeting  
 The team and product owner negotiate which item should to commited to the sprint. Top priority  
 item is moved from product backlog to sprint backlog and break them into small tasks so that  
 they make clear about task what they are going to do. 
                 product backlog                  sprint backlog  
 high priority   product backlog item      product backlog item      not started  
 .                      pbi                .                         tasks  tasks  
 .                             .                                     tasks  tasks  
 .  
 .  
 .  
 low priority 
 2.daily scrum  
 a.once in a day for 15 minutes standup meeting  
 b.Meet is between scrup development team to report eachother not to scrum master or product owner.  
 c. keys to share  
   a. Look what i did yesterday  
   b. what im going to do today  
   c challenges faced, blocked me and overcomes. 
 3.sprint review meeting  
 a.Team demonstarates potentially shippable product to product owner and any one who interested,  
 sometimes stack holders.  
 b. product owner declares which item is done and item meets acceptance criteria. We will get  
 feedback from stack holders about product development. 
 4.sprint retrospective meeting  
 a.Sprint ends with spring retrospective meeting.  
       what went well        what could be improved  
 b.will give feedbacks to eachothers.  
 c.This is the key of whole thing, team eventually takes ownership of whole process.  
 d.retrospective meeting gives feedback about process, team uses to built a product.scrum is framework  
 for learning about product and processes we use to build. 
 5.Backlog refinement meeting or Backlog grooming  
 a.Team and product owner get together and look into product backlog items for next couple of sprints.  
 b.break big product backlog items into small backlog items.ex : user stories.  
 c.This meeting can also do with sprint planning meeting or else alone a separate meeting.   

Saturday, 11 January 2014

How to add a custom font to Rails application by using google fonts

 for example i am using Freckle Face  
 http://www.google.com/fonts#QuickUsePlace:quickUse/Family:  
 Quick Use: Freckle Face  
 1. Choose the styles you want:  
 Impact on page load time  
 Tip: Using many font styles can slow down your webpage, so only select the font styles that you actually need on your webpage.  
 2. Choose the character sets you want:  
 Tip: If you choose only the languages that you need, you'll help prevent slowness on your webpage.  
 Latin (latin)  
 Latin Extended (latin-ext)  
 3. Add this code to your website:  
 Instructions: To embed your Collection into your web page, copy the code as the first element in the <head> of your HTML document.  
 <link href='http://fonts.googleapis.com/css?family=Freckle+Face' rel='stylesheet' type='text/css'>  
 4. Integrate the fonts into your CSS:  
 The Google Fonts API will generate the necessary browser-specific CSS to use the fonts. All you need to do is add the font name to your CSS styles. For example:  
 font-family: 'Freckle Face', cursive;  
 Instructions: Add the font name to your CSS styles just as you'd do normally with any other font.  
 Example:  
 h1 { font-family: ‘Metrophobic’, Arial, serif; font-weight: 400; }  
  example :  
 <head>  
  <meta charset='UTF-8' />  
  <link href='http://fonts.googleapis.com/css?family=Freckle+Face' rel='stylesheet' type='text/css'>  
 </head>  
 <body>  
 <div id="header">  
  <div id="nav">  
   <a href="#contact">Contact</a> <span style="word-spacing:normal; color:white; font-family: 'Freckle Face', cursive;, arial, serif; font-size:20px;"><--Click a link to see this page in action!</span>  
  </div>  
 </div>  
 </body>  

Thursday, 9 January 2014

Introspected tunnels to localhost for rails application

 About ngrok  
 ngrok creates a tunnel from the public internet (http://subdomain.ngrok.com) to a port on your local machine. You can give this URL to anyone to allow them to try out a web site you're developing without doing any deployment.  
 step 1  
 Download and Installation  
 For linux download if from below link and place it in required place  
 https://dl.ngrok.com/linux_386/ngrok.zip(https://ngrok.com/)  
 step 2  
 On Linux Unzip it  
 $ unzip /path/to/ngrok.zip  
 step 3  
 Run it!  
 $ ./ngrok -help  
 $ ./ngrok 3000  
 for example, if you are using port number as 3000  
 In your terminal you will see some thing like this  
 Tunnel Status         online                                    
 Version               ********                                   
 Forwarding          http://*********.ngrok.com -> 127.0.0.1:3000                 
 Forwarding          https://********.ngrok.com -> 127.0.0.1:3000                 
 Web Interface         **************                               
 # Conn            **                                      
 Avg Conn Time         7285.98ms        
 HTTP Requests                              
 -------------   
 *******************************  
 *******************************  
 step 4  
 By using this link you can give this URL to anyone to allow them to try out a web site you're developing without doing any deployment.  
 https://********.ngrok.com -> 127.0.0.1:3000    
 done.......  

Wednesday, 8 January 2014

How to add a custom font to Rails application

 Hi all,  
       I came accross this way of adding custom font to rails application. If u have another way of adding plz comment down.  
 step 1  
 select font type and download  
 for example  
 go to http://www.dafont.com  
 select font and download font  
 step 2  
 go to http://www.fontsquirrel.com/  
 select - web font generator - select font u download(unzip file downloaded from http://www.dafont.com).  
 step 3  
 This site wil generate another zip which contain all required for that font style.  
 From that zip, unzip and open css, copy css into your html or css file of that html.  
 step 4  
 (http://stackoverflow.com/questions/12329137/how-to-add-a-custom-font-to-rails-app)  
 config/application.rb  
 config.assets.enabled = true  
 config.assets.paths << "#{Rails.root}/app/assets/fonts"  
 step 5  
 example  
 <html lang="en">  
 <head>  
 <style>  
 @font-face {  
      font-family: 'a_sensible_armadilloregular';  
      src: url('/assets/para/a_sensible_armadillo-webfont.eot');  
      src: url('/assets/para/a_sensible_armadillo-webfont.eot?#iefix') format('embedded-opentype'),  
      url('/assets/para/a_sensible_armadillo-webfont.woff') format('woff'),  
      url('/assets/para/a_sensible_armadillo-webfont.ttf') format('truetype'),  
      url('/assets/para/a_sensible_armadillo-webfont.svg#a_sensible_armadilloregular') format('svg');  
      font-weight: normal;  
      font-style: normal;  
    }  
 .content p {  
      font-family: 'a_sensible_armadilloregular';  
      font-size: 42px;  
    }  
 </style>  
 </head>  
 <body>  
 <div class="content">  
   <p>sample text</p>  
  </div>  
 </body>  
 </html>