Tag: Rails

Easy way to extend and overwrite bb-ruby bbcode gem translations in Ruby on Rails

When you go to bb-ruby gem readme, there is an instruction how to extend it with your own translations:

my_block = {
  'Quote' => [
    /\[quote(:.*)?=(.*?)\](.*?)\[\/quote\1?\]/mi,
    '<div class="quote"><p>\2</p><block>\3</block></div>',
    'Quote with citation',
    '[quote=mike]please quote me[/quote]',
    :quote
  ],      
}

text.bbcode_to_html(my_blockquote)

This method works quite good but well... it's way to inconvenient. Where should we put our translation? In our model? Should we create a different model which would store our costume translations? Nah... There is really easy and clean way to add new (and overwrite already existing) translations into a bbcode parser.

Create in your app initializers directory (/config/initializers/) a file called bb-ruby.rb. Below you can see an example with [spoiler][/spoiler] tag:

module BBRuby
  if @@tags
    @@tags['Spoiler'] = [
      /\[spoiler\](.*?)\[\/spoiler\1?\]/mi,
      '<span class="spoiler">\1</span>',
      'spoiler',
      '[spoiler]spoiler[/spoiler]',
      :spoiler]
  end
end

And how to overwrite existing translation? Just replace it with new one. Below example which replaces standard "Link" rule, with same rule but with rel="nofollow":

@@tags['Link'] = [
  /\[url=(.*?)\](.*?)\[\/url\]/mi,
  '<a href="\1" rel="nofollow">\2</a>',
  'Hyperlink to somewhere else',
  'Maybe try looking on [url=http://google.com]Google[/url]?',
  :link]

Handling large seed files in Ruby on Rails

Sometimes seed files can get messy and big. It can be real pain it the ass to manage them. Here is fast way to split single seeds.rb file:

  1. Create directory called seeds in your db/ directory (mkdir ./db/seeds)
  2. Remove all stuff from seeds.rb and move it into your newly created files under db/seeds/ directory (put them accordingly to your own app logic)
  3. Paste code presented below into seeds.rb file
  4. Run rake db:seed

Seeds.rb file source code:

# coding: utf-8

%w{
  filename1 filename2 filename3...filenameN
}.each do |part|
  require File.expand_path(File.dirname(__FILE__))+"/seeds/#{part}.rb"
end

Why haven't I use auto-include and instead I've listed all the files? Well I wanted to maintain my seed parts load order so those parts will be loaded accordingly to my order (not based on file names).

Copyright © 2025 Closer to Code

Theme by Anders NorenUp ↑