Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS 

Format IPv4 address in octal binary format and vice versa (Ruby / Rails)

Format an IPv4 address like 192.168.1.1 in dotted binary format like 11000000.10101000.00000001.00000001
You also need this class: http://snippets.dzone.com/posts/show/2472
For Rails: Put this in your controller!


  # convert a dotted decimal IPv4 address to dotted binary format
  def ipv4_to_binary(ipv4addr)
    ia = ipv4addr.to_s.split('.')
    if ia.size != 4
      return "0.0.0.0"
    end
    output = ""
    i = 1
    for octett in ia
      output = output + octett.to_i.to_s(2).using("########","0",true)
      if i < 4
        output = output + "."
      end
      i += 1
    end
    return output
  end
  
  
  # convert a IPv4 adress in binary dotted format to a dotted IPv4 address
  def binary_to_ipv4(ipv4addr)
    ia = ipv4addr.to_s.split('.')
    if ia.size != 4
      return "0.0.0.0"
    end
    output = ""
    i = 1
    for octett in ia
      output = output + octett.to_s.to_i(2).to_s
      if i < 4
        output = output + "."
      end
      i += 1
    end
    return output
  end

Generate a list of Rails controllers and methods

This code goes over the App/controllers directory and extracts a list
of all controllers and their methods.

use this script from rails console.

I have used this script to generate a migration file with default authorization roles & rights.

controllers = Dir.new("#{RAILS_ROOT}/app/controllers").entries
controllers.each do |controller|
 if controller =~ /_controller/ 
  cont = controller.camelize.gsub(".rb","")
  puts cont
  (eval("#{cont}.new.methods") - 
    ApplicationController.methods - 
    Object.methods -  
    ApplicationController.new.methods).sort.each {|met| 
       puts "\t#{met}"
    }
end

end



to use it to create a Right object I used the following adjustments:

controllers.each do |controller|
    if controller =~ /_controller/ 
    name = controller.camelize.gsub(".rb","")
     (eval("#{name}.new.methods") - 
       Object.methods -  
       ApplicationController.new.methods).sort.each {|met| 
          name_short = name.gsub("Controller","").downcase
          #it is possible to call the create directly from this script
          #I wanted to review and revise the names. 
          puts "#{met}_#{name_short}=Right.create(:name=>\"#{met} #{name_short}\",
                                                  :controller=>\"#{name_short}\",
                                                  :action=>\"#{met}\")"}
  end
  end

#post method in tests with a different controller

I wanted a #login method in test_helper that would allow me to easily login from any of my functional tests. However, the #post method won't allow you to set a different controller than the one in the @controller instance variable that's defined in your test's #setup. Well, by looking at how the #process method works, you can see that it just grabs the controller from @controller. Redefine that, and you're good to go:
old_controller = @controller
@controller = LoginController.new
post(
  :attempt_login,
  {:user => {:name => 'joe', :password => 'password'}}
)
@controller = old_controller

If you have several login methods, such as a #login_admin and #login_regular, you could make a wrapper to reduce duplication:
def wrap_with_controller( new_controller = LoginController )
  old_controller = @controller
  @controller = new_controller.new
  yield
  @controller = old_controller
end

def login_admin
  wrap_with_controller do
    post(
      :attempt_login,
      {:user => {:name => 'root', :password => 'password'}}
    )
  end
end

def login_regular
  wrap_with_controller do
    post(
      :attempt_login,
      {:user => {:name => 'joe', :password => 'password'}}
    )
  end
end

rails generator syntax

// generate application
rails projectname


// generate migration.
ruby script/generate migration migration_name
ruby script/generate migration add_price


// generate model
// we can give a list of columns and types
// :string, :text, :integer, :decimal, :float, :date, ...
ruby script/generate model model_name
ruby script/generate model user name:string hashed_password:string salt:string


// generate controller
ruby script/generate controller controller_name method_name(s)
ruby script/generate controller store index


// generate scaffold
ruby script/generate scaffold model_name controller_name
ruby script/generate scaffold product admin

how to escape from AJAX URL

From Dylan Stamat's post on the Ruby on Rails list


Within my "login.rjs" template that get's invoked after my login process, it returns to the same page with an error message on error, or... if the login was successful, it needs to "redirect" to another controller... which is pretty much impossible to do otherwise. so, my " login.rjs" looks like:

if @logged_in_client
  page.replace_html "message", :partial => 'shared/bad_login'
else
  page.redirect_to "whatever you want here"
end

------ End Message--------
Here is my two cents:
Technically, you can do this without a RJS template at all, because it is such a simple example. Use this in your controller

render :update do |page|
  if @logged_in_client
    page.replace_html "message", :partial => 'shared/bad_login'
  else
    page.redirect_to "whatever you want here"
  end
end

Firing a controller's action from the console

It seems like a simple task, but here's how you can simulate the calling of a controller's action:

ruby script/console

irb> require 'action_controller/test_process'
irb> require 'application'
irb> require 'site_controller'
irb> request = ActionController::TestRequest.new
irb> response = ActionController::TestResponse.new
irb> request.env['REQUEST_METHOD'] = 'GET'
irb> request.action = "late_employee"
irb> InfoController.process(request,response)


Basically, it's like getting inside of a TestUnit method, but you have to do the dirty work yourself.

Render a partial to an instance variable

Normally, if you call "render_partial" within a controller, nothing but the partial will be rendered.

Occasionally, it is useful to render a partial to an instance variable as a string so that the view can still be rendered as normal, and the string can be passed in to the view.

  add_variables_to_assigns
  @content_for_navbar = @template.render_partial 'layouts/public_navbar'
« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS