select!
Posted by jacqui maher on April 11, 2008 at 01:55 PM
I found myself having to reverse logic in some code I wrote recently due to the wants of the client doing a 180. I had been using reject! to remove elements in an array, and realized that I now wanted to use select! - only there is no select!
I started to write:
arr = arr.select{|a| some.method.here }
when it occured to me that was a little clunky. I wanted select in place.
Here’s my version of it:
1 class Array
2 def select!(&block)
3 selected = self.select(&block)
4 if selected.size > 0
5 replace(selected)
6 else
7 nil
8 end
9 end
10 end
Usage:
1 >> arr = ["Ren", "Easy-E", "Ice Cube", "DJ Yella", "Dr Dre"]
2 # => ["Ren", "Easy-E", "Ice Cube", "DJ Yella", "Dr Dre"]
3
4 >> arr.select!{|a| a =~ /^D/ }
5 # => ["DJ Yella", "Dr Dre"]
6
7 >> arr.select!{|a| a =~ /^J/ }
8 # => nil
9
10 >> arr
11 # => ["DJ Yella", "Dr Dre"]
snippet: grab webpage and save it for future traversing
Posted by jacqui maher on March 04, 2008 at 03:47 PM
I use this method to grab a webpage and then access it later. It’s useful if you’re trying to scrape a page, for example, and don’t want to keep hitting it over the network. Note that I use this as part of a class which initializes the variable @local_dir at instance creation.
1 def get_local_or_remote(id, webpage_uri_format)
2 html = ""
3 if File.exists? "#{@local_dir}/#{id}.html"
4 html = File.read("#{@local_dir}/#{id.html")
5 else
6 webpage_uri = if webpage_uri_format.match(/:id/)
7 webpage_uri_format.gsub(":id", id)
8 else
9 webpage_uri_format
10 end
11
12 html = insist(:delay => 60) do
13 Net::HTTP.get_response(URI.parse(webpage_uri)).body
14 end
15
16 stfile = File.new("#{@local_dir}/#{id}.html", "wb")
17 stfile.puts(html)
18 stfile.close
19 end
20
21 return html
22 end
snippet: saving data to a file to use as an input later
Posted by jacqui maher on March 04, 2008 at 01:41 PM
I find myself doing this often.
1 >> data = Model.find_all_by_something("Something")
2 # => [... results...]
3
4 >> File.open("#{RAILS_ROOT}/db/data/somethings.yml", "w") do |f|
5 > f.puts data.to_yaml
6 > end