require 'action_view'
require 'action_controller/mime' # for Rails 2
render :file=>'foo.html.erb', :locals=>{:user=>User.first}
render :file=>'lib/data_feed.xml.builder', :type=>:rxml, :locals=>{:user=>User.first)
def render(options)
klass = Class.new(ActionView::Base)
klass.class_eval{ def url_for(x);x;end } # to be able to use link_to
klass.new.render(options)
end
Category Archives: Ruby
Quick Markdown Preview For Github Readme
I write my Readme in marddown, and often it gets messed up and then I have to commit & push until its finally right, so I wrote a small script to get a preview (using githubs markdown library)!
Usage
markdown README.markdown ... chrome pops up with the html preview
Install
gem install redcarpet
Put this into e.g. ~/bin/markdown and do a chmod +x on it
#!/usr/bin/env ruby
raise "gime a file!!" unless ARGV[0]
exec "redcarpet #{ARGV[0]} > /tmp/markdown.html && chromium-browser /tmp/markdown.html"
Alternatively: Interactive Live Preview<
Array.to_ordered_hash replacement for Rails 2.3 ActiveSupport::OrderedHash.new
The simple
ActiveSupport::OrderedHash.new [[1,2]]
does no longer work in Rails 2.3, so I built a small patch for array that make OrderedHash creation simple again.
Code
class Array
def to_ordered_hash
ActiveSupport::OrderedHash[self]
end
end
Usage
hash = [[:key, 'value'], [:key2, :value2], [1, 2]].to_ordered_hash
hash == {:key=>'value', :key2=>:value2, :1=>2}
Ruby File.write
Write to a file, simple and elegant as File.read:
def File.write(file,data)
File.open(file,'w'){|f|f.write(data)}
end
File.write('xxx',"AAA")
File.write('xxx',File.read('xxx')+"AAA")
...
All ActionView Helpers on Strings
Insert all the helpers you want and “go!”.strip_tags.auto_link.truncate(25)
# ActionView text helpers
# https://grosser.it/2009/05/30/all-actionview-helpers-on-strings/
class String
%w[auto_link excerpt highlight sanitize simple_format strip_tags word_wrap].each do |method|
define_method method do |*args|
ActionController::Base.helpers.send method, self, *args
end
end
# called with a number or with :length=>10
def truncate(*args)
if args.first.is_a?(Hash)
ActionController::Base.helpers.truncate(self, *args)
else
ActionController::Base.helpers.truncate(self, :length=>args[0])
end
end
end