you are here: codestackercodes [RSS] → tag ruby [RSS]

Creating SQL inserts from Rails

cc = CourseEnrollmentEmailCcUser.new(id: 1, couse_enrollment_email_id: 1)

puts cc.class.arel_table.create_insert.tap { |im|
  im.insert(cc.send(:arel_attributes_with_values_for_create, cc.attribute_names)) 
}.to_sql

simple http monitor based on keyword

http://leonardofaria.net/2015/07/10/uptime-monitoring-tools/

gem 'mechanize', '2.7.2'
require 'mechanize'
require 'pony'

def sendmail(to, subject, body)
	Pony.mail({
	  :to => to,
	  :via => :smtp,
	  :subject => subject,
	  :body => body,
	  :charset => 'UTF-8',
	  :via_options => {
		:address => 'smtp.sendgrid.net',
			:port => '587',
			:domain => 'heroku.com',
			:user_name => ENV['SENDGRID_USERNAME'],
			:password => ENV['SENDGRID_PASSWORD'],
			:authentication => :plain,
			:enable_starttls_auto => true
	  }
	})
end

mechanize = Mechanize.new{|a| a.ssl_version, a.verify_mode = 'SSLv3', OpenSSL::SSL::VERIFY_NONE}
page = mechanize.get('https://www.yourwebsite.com/mytesturl')

content = ""

if page.body.include?('refused')
	content = 'Error: Connection Refused'
end

if content
	puts content
	sendmail("email@domain.com", "Monitor", content)
end

how to use number_to_currency in controller

include ActionView::Helpers::NumberHelper

simple random string method

def rand_str(length)
	return rand(36**length).to_s(36)
end

simple random password method

def random_password(size = 8)
	charset = %w{ 2 3 4 6 7 8 9 A B C D E F G H J K L M N P Q R T V W X Y Z}
	(0...size).map{ charset.to_a[rand(charset.size)] }.join
end

rails 3 validates method

validates :login, :presence => true, :length => {:minimum => 4}, :uniqueness => true, :format => { :with => /[A-Za-z0-9]+/ }

# :presence => true

# :uniqueness => true

# :numericality => true

# :length => { :minimum => 0, maximum => 2000 }

# :format => { :with => /.*/ }

# :format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i } # email format

# :format => { :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix } # url format

# :inclusion => { :in => [1,2,3] }

# :exclusion => { :in => [1,2,3] }

# :acceptance => true

# :confirmation => true

rails 3 money validation

validates :price, :presence => true, :format => { :with => /[0-9\,]*/ }

grep an object's available methods

Object.methods.grep /inspect/
=> ["inspect", "pretty_inspect", "pretty_print_inspect"]

return the url base in ruby

>> url = "http://www.codestacker.com/tag/ruby"
>> url[/https?:\/\/.[^\/]+/]
=> "http://www.codestacker.com"

writing a file

r - Open a file for reading. The file must exist.
w - Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.
a - Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist.
r+ - Open a file for update both reading and writing. The file must exist.
w+ - Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.
a+ - Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. You can reposition (fseek, rewind) the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist.

doc = "hello world"

File.open(my_file, 'w') {|f| f.write(doc) }

humanize secs

source: http://stackoverflow.com/questions/4136248/how-to-generate-a-human-readable-time-range-using-ruby-on-rails

def humanize secs
  [[60, :seconds], [60, :minutes], [24, :hours], [1000, :days]].map{ |count, name|
    if secs > 0
      secs, n = secs.divmod(count)
      "#{n.to_i} #{name}"
    end
  }.compact.reverse.join(' ')
end

p humanize 1234
#=>"20 minutes 34 seconds"

p humanize 12345
#=>"3 hours 25 minutes 45 seconds"

p humanize 123456
#=>"1 days 10 hours 17 minutes 36 seconds"

p humanize(Time.now - Time.local(2010,11,5))
#=>"4 days 18 hours 24 minutes 7 seconds"

sending email with pony

Pony.mail(:to => 'email@provider.com', :via => :smtp, :via_options => {
:address => 'smtp.gmail.com',
:port => '587',
:enable_starttls_auto => true,
:user_name => 'id_gmail',
:password => 'parola_gmail',
:authentication => :plain, # :plain, :login, :cram_md5, no auth by default

:domain => "HELO", # don't know exactly what should be here

},
:subject => 'hi', :body => 'Hello there.')

Array method to return array elements as quoted strings

class Array
  def to_quoted_s(q="'")
    "#{q}#{self.join("#{q}, #{q}")}#{q}"
  end
end

# Example:


a = ['a', 'b', 'c', 'd', 'e']
puts a.to_s # abcde

puts a.to_quoted_s # 'a', 'b', 'c', 'd', 'e'

puts a.to_quoted_s("\"") # "a", "b", "c", "d", "e"

listing files in a directory with rails

via Shairon Toledo @ rails-br

Dir.glob("*").each{|f|  puts "Name: #{f} | Created at: #{File.ctime(f)} | Updated at: #{File.mtime(f)}"   }

post in twitter using rest_client

http://github.com/adamwiggins/rest-client

require "rubygems"
require "rest_client"

RestClient::Resource.new("http://twitter.com/statuses/update.json", :user => "user", :password => "pass").post :status => "Hello, there!"

i18n in labels

rails 2.3.4 doen't have i18n support in labels

http://lawrencesong.net/2009/04/i18n-label-in-rails-monkey-patch/

module ActionView 
  module Helpers 
    class InstanceTag 
      def to_label_tag_with_i18n(text = nil, options = {}) 
        text ||= object.class.human_attribute_name(method_name) if object.class.respond_to?(:human_attribute_name) 
 
        to_label_tag_without_i18n(text, options) 
      end 
 
      alias_method_chain :to_label_tag, :i18n 
    end 
  end 
end

paperclip refresh all images

run this task

rake paperclip:refresh class=MyClass

use default_scope to set up default find conditions such as order

class MyModel < ActiveRecord::Base
  default_scope :order => 'created_at desc'
end

humanized attributes

class User < ActiveRecord::Base

  HUMANIZED_ATTRIBUTES = {
    :email => "E-mail address"
  }

  def self.human_attribute_name(attr)
    HUMANIZED_ATTRIBUTES[attr.to_sym] || super
  end

end

paperclip ie validation

validates_attachment_content_type :image,
  :content_type => [
    'image/jpeg',
    'image/pjpeg', # for progressive jpeg (IE mine-type for regular jpeg) 

    'image/png',
    'image/x-png', # IE mine-type for PNG

    'image/gif'
]
Displaying Code 1 - 20 of 69 in total