Forkme Fork me on Github

Latest posts

Truncate your html with Nokogiri

I was looking for a better solution today to truncate my blog posts on seogrady.com and came across a good post by here. The basic idea was to use Nokogiri to parse a html string and count the characters that exist once the html tags have been stripped.

To use the truncate html helper simply add the following to your code and replace the appropriate arguments.

= truncate_html post.body, 500, "...<a href='#{post_path(post)'>view more</a>}"

I also wanted to find a solution to remove the code syntax within my posts so the helper would not leave code fragments visible to the reader. So I edited the original code to allow for an option to remove syntax highlighting. The helper will also nest the ellipsis inside the last html element within your selection.

To do this I added a block that uses the class name div.CodeRay and removed the nodes. As an example this is how you can remove a html node using Nokogiri.

@doc = Nokogiri::HTML::DocumentFragment.parse <<-EOHTML
<body>
  <h1>Nokogiri</h1>
  <div class="example">My first div.</div>
  <div class="example">My second div.</div>
</body>
EOHTML

@doc.css("div.example").each do |node|
  node.remove
end

I thought it might also be a good idea to truncate the text at say 500 characters, then if the helper detects Coderay it will remove the remaining html elements. Perhaps I will do this in the future sometime :)

To get the helper download the gist from Github.

Ruby Class Inheritance

I was reading a post on StackOverFlow today that highlighted a few good examples of ruby class inheritance. For me, I was always a little puzzled by the many uses for the double less than << in ruby.

For example, it can be used to add methods to an existing class instance by doing this:

class MyClass
end

someinstance = MyClass.new

class << someinstance
  def foo
    "Hello."
  end
end 

Then foo can be called be called once the code has been executed.

someinstance.foo   => "Hello."

This illustrates how flexible and expressive ruby can be. Probably the most common use for << in ruby is in defining class methods within a class. For example, if you want to define a group of class methods do the following.

class MyClass
  def foo
    puts "I am an instance method"
  end

  class << self
    def bar
      puts "I am #{self}"
    end
  end
end

The ouput would be:

t = MyClass.new
t.foo # => "I am an instance method"
t.class.bar # => "I am MyClass"
t.bar # => NoMethodError: undefined method 'bar'

An alternative way to define a class method is:

class MyClass
    def self.bar
      puts "I am #{self}"
    end
end

Lastly, if you want to access a class method without creating an instance of the class. You can simply do the following:

MyClass.bar # => "I am MyClass"

Thanks and I hope this post was useful :-)