These are simple loops in Ruby. First is a loop using the for-each syntax you may be familiar with, second is the much cooler "each" Enumeration that is far cooler and more "pure" (whatever that means).
# for-each loop
for i in list
# do something with item 'i'
p i
end
# enumeration loop
list.each do |i|
# do something with item 'i'
p i
end
This is a script to manage a team's set of ruby gems by pulling from a MediaWiki article that contains YAML, of the following form:
gems: {fastercsv: '1.2.0', soap4r: '>1.5.5' }
require 'net/http'
require 'yaml'
# install a given gem and version, may also give a URL
def gem_install(gem, version, url=nil)
# only install if not already installed
listed = `gem list #{gem} --no-details --local`
unless listed =~ %r"^#{gem} "
puts "== Installing #{gem}"
puts `sudo gem install #{gem} -f -y -v '#{version}'`
end
end
# First try and find a local or given gems.yml file
gems_config_file = ARGV[0].nil? ? 'gems.yml' : ARGV[0]
gems = nil
begin
gems = YAML::load_file( gems_config_file )
rescue Errno::ENOENT => e
puts "Could not find file... looking remotely in the wiki Gems.yml"
url = URI.parse('http://wikiserver/')
res = Net::HTTP.start(url.host, url.port) do |http|
http.get("/index.php?action=raw&title=Gems.yml")
end
data = res.body
gems = YAML::load(data)
end
gems['gems'].each { |gem| gem_install(gem[0], gem[1]) }
If you love messing with time in Ruby as much as I do you will appreciate this. This is a 12 hour time select. What separates this helper from time_select is that the hour select has 1am-12am and 1pm-12pm options. Therefore, the am/pm selection is removed. In addition, you have the ability to select minutes at different intervals easily. Enjoy
##################################### VIEW ##########################################
#12hr time with 15min intervals
<%= example_time_select(Time.now) %>
##################################### HELPER ########################################
def example_time_select(time)
return select_hour_with_twelve_hour_time(time, :field_name => 'hour',:prefix =>
'time') + ": " + select_minute_with_interval_of_fifteen(time,
:field_name => 'minute', :prefix => 'time')
end
def select_hour_with_twelve_hour_time(time, options = {})
val = time ? (time.kind_of?(Fixnum) ? time : time.hour) : ''
if options[:use_hidden]
hidden_html(options[:field_name] || 'hour', val, options)
else
hour_options = []
0.upto(23) do |hour|
ampm = hour <= 11 ? ' AM' : ' PM'
ampm_hour = hour == 12 ? 12 : (hour / 12 == 1 ? hour % 12 : hour)
hour_options << ((val == hour) ?
%(<option value="#{hour}"
selected="selected">#{ampm_hour}#{ampm}</option>\n) :
%(<option value="#{hour}">#{ampm_hour}#{ampm}</option>\n))
end
select_html(options[:field_name] || 'hour', hour_options, options)
end
end
def select_minute_with_interval_of_fifteen(time, options = {})
val = time ? (time.kind_of?(Fixnum) ? time : time.min) : ''
if options[:use_hidden]
hidden_html(options[:field_name] || 'minute', val, options)
else
minute_options = []
minute = 0
4.times do
if minute == 0
minute_options << ((val == minute) ?
%(<option value="#{minute}" selected="selected">0#{minute}</option>\n) :
%(<option value="#{minute}">0#{minute}</option>\n))
else
minute_options << ((val == minute) ?
%(<option value="#{minute}" selected="selected">#{minute}</option>\n) :
%(<option value="#{minute}">#{minute}</option>\n))
end
minute += 15
end
end
select_html(options[:field_name] || 'minute', minute_options, options)
end
This two little nuggets does the inverse of column.human_name and gives you the data type if you have the human name and not column object.
def self.get_column_name(column_name)
return column_name.downcase.gsub(/ /,'_')
end
def self.get_column_type(column_name)
for column in Object.content_columns
if column.name == get_column_name(column_name)
return column.klass
end
end
end
with_scope lets you bind a block of code operating on an active record model to a particular subset of that model’s collection. For instance, using the standard blog application example, if I have a controller method that performs a series of operations on a single user’s articles I would need to pass in the user id condition on every operation. with_scope lets us extract that parameter.
# Notice we have to pass in the 'user_id' on both the find and create method.
def create_avoid_dups
user_id = current_user.id
# Find all user's posts
user_posts = Post.find(:all, :conditions => ["user_id = ?", user_id])
# Do some logic ...
# then create new
@post = Post.create(:body => params[:body], :user_id => user_id)
end
# with_scope lets us extract that parameter:
def create_avoid_dups
Post.with_scope(:find => {:conditions => "user_id = #{current_user.id}"},
:create => {:user_id => current_user.id}) do
# Find all user's posts
# No longer need user_id condition since we're in scope
user_posts = Post.find(:all)
# Do some logic ...
# then create new, without specifying user_id
@post = Post.create(:body => params[:body])
end
end