HoboFields – Rich Types

This doctest describes the rich types bundled with HoboFields, and the process by which you can create and register your own types.

doctest_require: 'prepare_testapp'

>>
 ActiveRecord::Migration.create_table :articles do |t|
   t.text :body
   t.string :status
 end
>>

to_html method

The rich types provide a to_html method. If you are using the full Hobo stack you don’t need to be aware of this unless you’re defining your own rich types – the <view> tag uses to_html to render a rich type. If you are not using DRYML and Rapid, you can simply call to_html in your views, e.g.

    <div class="post-body"><%= @post.body.to_html %></div>

If you ever decide to change from, say, plain text to markdown formatted, your view won’t need to change.

Defining your own Rich Type

Defining a rich type is very simple. We’ll show an example here before we go through the bundled types so that you start with the idea that there’s really nothing sophisticated going on here.

This class defines the methods to_html to customize the way the type is rendered, and validate to provide a custom validation. It also defined the COLUMN_TYPE constant to tell the migration generator what underlying type should represent these values in the database.

    # Loud text always renderd in caps.
    # It's rude to shout too much so it's not allowed to be
    # longer than 100 characters
    >>
     class LoudText < String

       COLUMN_TYPE = :string

       HoboFields.register_type(:loud, self)

       def validate
         "is too long (you shouldn't shout that much)" if length > 100
       end

       def format
         # make sure we have enough exclamation marks
         self =~ /!!!$/ ? self + "!!!" : self
       end

       def to_html(xmldoctype = true)
         upcase
       end

     end
    >>

    >> LoudText.new("foO<BAa").to_html
    => "FOO<BAA"
    >> LoudText.new("foO<BAa").to_html.html_safe?
    => false

If you place this class in app/rich_types/loud_text.rb, Hobo will load it automatically.

That’s all there is to it. Defining to_html, format and validate are optional, defining COLUMN_TYPE and calling HoboFields.register_type are not.

We inherit from String in this instance. This does not work for all types – for example, with Fixnum, you should inherit from DelegateClass(Fixnum) instead.

The format function is added as a before_validation hook. Ensure that multiple invocations of your format function is safe – shout.format.format should return the same as shout.format.

You can use LoudText in your model with

fields do
  shout :loud
end

Bundled types

Here we’ll give a quick overview of the bundled types. Remember that along with the specific features the type provides (e.g. validation), the simple fact that the type exists is also useful in the other layers of Hobo. For example HoboFields::Types::PasswordString doesn’t add any features to String, but the fact that a specific type exists for passwords means that the view layer can automatically render an <input>.

HoboFields::Types::EmailAddress

Provides validation of correct email address format.

    >> good = HoboFields::Types::EmailAddress.new("foo@baa.com")
    >> bad  = HoboFields::Types::EmailAddress.new("foo.baa.com")
    >> !!good.valid?
    => true
    >> good.validate
    => nil
    >> !!bad.valid?
    => false
    >> bad.validate
    => "is invalid"

    >> nasty = HoboFields::Types::EmailAddress.new("foo<nasty>&lt;nasty&gt;@baa.com")
    >> nasty.to_html
    => "foo&lt;nasty&gt;&amp;lt;nasty&amp;gt; at baa dot com"
    >> nasty.to_html.html_safe?
    => true

HoboFields::Types::HtmlString

HtmlString provides no special behavior. The main reason for using this type is that the to_html method does not do any html-escaping. Use this for columns that store raw HTML in the database.

    # no safety treatments are done by `to_html`.
    # even if `nasty.to_html` is actually unsafe, it is marked as html_safe.
    >> nasty = HoboFields::Types::HtmlString.new("p1<p>p2</p>p3<nasty>p4</nasty>p5&lt;script&gt;p6<script>p7</script>p8")
    >> nasty.to_html
    => "p1<p>p2</p>p3<nasty>p4</nasty>p5&lt;script&gt;p6<script>p7</script>p8"
    >> nasty.to_html.html_safe?
    => true

    >>
     class Article < ActiveRecord::Base
       fields do
         body HoboFields::Types::HtmlString
       end
       attr_accessible :body
     end
    >> article = Article.create!(:body => "</div>>>p1<p>p2</p>p3<nasty>p4</nasty>p5&lt;script&gt;p6<script>p7</script>p8")
    # some unsafe html fragements are removed on save,
    # but there's no guarantees that it is well-formed
    >> article.body
    => "</div>>>p1<p>p2</p>p3p4p5&lt;script&gt;p6p8"
    >> article.body == article.body.to_html
    => true
    >> article.body.to_html.html_safe?
    => true

HoboFields::Types::MarkdownString

HoboFields::Types::MarkdownString provides a to_html that renders markdown syntax into html. It looks for RDiscount, Kramdown, Maruku or BlueCloth in that order.

    >> markdown = HoboFields::Types::MarkdownString.new %(
      This is a heading
      =================

      And text can be *emphasised*
      )
    >> markdown.to_html.strip
    => "<h1>This is a heading</h1>\n\n<p>And text can be <em>emphasised</em></p>"
    >> markdown.to_html.html_safe?
    => true

    # unsafe html behaviour depends on the parser used.
    >> markdown = HoboFields::Types::MarkdownString.new("</div>p1<script>p2")
    >> markdown.to_html
    => "<p>&lt;/div&gt;p1</p>\n"
    # Bluecloth would return
    # => "<p></div>p1</p>"
    >> markdown.to_html.html_safe?
    => true

HoboFields::Types::TextileString

HoboFields::Types::TextileString provides a to_html that renders markdown syntax into html. It requires the redcloth gem.

    >> textile = HoboFields::Types::TextileString.new %(
     Text can be _emphasised_
     )
    >> textile.to_html
    => "<p>Text can be <em>emphasised</em></p>"
    >> textile.to_html.html_safe?
    => true

    # some unsafe html fragements are removed by `to_html`,
    # but there's no guarantees that it is well-formed
    >> textile = HoboFields::Types::TextileString.new("</div>>>p1<script>p2")
    >> textile.to_html
    => "<p></div>&gt;&gt;p1</p>"
    >> textile.to_html.html_safe?
    => true

HoboFields::Types::Text

HoboFields::Types::Text provides a to_html method with HTML escaping and conversion of newlines to <br /> tags.

    >> text = HoboFields::Types::Text.new %(Tom & Jerry

     Cat & Mouse)
    >> text.to_html
    => "Tom &amp; Jerry<br />\n<br />\n         Cat &amp; Mouse"
    >> text.to_html.html_safe?
    => true

    # `to_html` always returns actually html-safe string
    >> text = HoboFields::Types::Text.new("</div>>>p1<script>p2")
    >> text.to_html
    => "&lt;/div&gt;&gt;&gt;p1&lt;script&gt;p2"
    >> text.to_html.html_safe?
    => true

HoboFields::Types::PasswordString

HoboFields::Types::PasswordString provides a simple to_html to prevent accidental display of a password. It simply returns “[password hidden]”. The type is also used to indicate the need for an <input>

    >> HoboFields::Types::PasswordString.new("pass<word>").to_html
    => "[password hidden]"
    >> HoboFields::Types::PasswordString.new("pass<word>").to_html.html_safe?
    => true

HoboFields::Serialized

This type lets you store an arbitrary object as serialized text into the database column. You can optionally pass the :class option to restrict the column type.

>>
 class Vault1 < ActiveRecord::Base
   fields do
     content :serialized
   end
   attr_accessible :content
 end

>> migrate
>> Vault1.create!(:content => {:key => "in Vault"})
>> Vault1.first.content
=> {:key => "in Vault"}

>>
 class Vault2 < ActiveRecord::Base
   fields do
     content :serialized, :class => Hash
   end
   attr_accessible :content
 end

>> migrate
>> Vault2.create!(:content => {:key => "in Vault"})
>> Vault2.first.content
=> {:key => "in Vault"}
>> puts Vault2.count
>> v = Vault2.create!(:content => 17) rescue 'broken' # ActiveRecord::SerializationTypeMismatch
=> 'broken'

Enum Strings

HoboFields::Types::EnumString is not a rich type that you use directly. It’s a “type generator”, rather like Ruby’s Struct. It’s used for the common situation in database driven apps that you want an enumerated type, but it’s not worth going to the extra bother of a separate table enumerating the values. For example you could create a type to represent the status of an article:

    >> ArticleStatus = HoboFields::Types::EnumString.for('', :draft, :approved, :published)
    => ArticleStatus

Note that, like all dynamically created classes in Ruby, the class is anonymous until assigned to a constant:

    >> klass = HoboFields::Types::EnumString.for(:draft, :approved, :published)
    => #<EnumString draft approved published>
    >> AritcleStatus = klass
    >> ArticleStatus
    => ArticleStatus

The values in the enum are available as class constants:

    >> ArticleStatus::DRAFT
    => "draft"
    >> ArticleStatus::DRAFT.class
    => ArticleStatus

There are also instance methods to check for each of the values:

    >> a = ArticleStatus::APPROVED
    >> a.is_draft?
    => false
    >> a.is_approved?
    => true

They can be constructed from strings:

    >> a = ArticleStatus.new("approved")
    >> a.is_approved?
    => true

Equality is string equality, with symbols first converted to strings:

    >> a == "approved"
    => true
    >> a == :approved
    => true

Note that every enum you create is a subclass of HoboFields::Types::EnumString:

    >> a.is_a?(HoboFields::Types::EnumString)
    => true

EnumString’s have a validate function defined to fit in with the ActiveRecord validation framework.

   >> a.validate
   => nil
   >> ArticleStatus.new("junked").validate
   => "must be one of '', draft, approved, published"

Using EnumString in your models

HoboFields::Types::EnumString extends the field declaration DSL with a shorthand for creating enum types:

    >>
     class Article < ActiveRecord::Base
       fields do
         status enum_string(:draft, :approved, :published)
       end
     end
    >> Article.attr_type :status
    => #<EnumString draft approved published>

Sometimes it’s nice to have a proper type name. Here’s one way you might go about it:

    >>
     class Article < ActiveRecord::Base
       Status = HoboFields::Types::EnumString.for(:draft, :approved, :published)
       fields do
         status Article::Status
       end
     end
    >> Article.attr_type :status
    => Article::Status

    >> Article::Status::PUBLISHED.to_html
    => "published"
    >> Article::Status::PUBLISHED.to_html.html_safe?
    => true

Translating EnumString’s

Named EnumString’s may be translated. Here is an example fr.yml:

fr:
  article/statuss:
    draft: "esquisse"
    approved: "approuvé"
    published: "publiés"

(Note that in this case, the field name ‘status’ is pluralized, but very simply by adding an ‘s’, not an ‘es’ as would be gramatically correct.)

Alternatively, the translations may be supplied in ruby:

>> Article::Status.translated_values = { "draft"=>"esquisse", "approved"=>"approuvé", "published"=>"publiés" }

EnumString’s can be created with the translated values. Internally, they always store the native version.

>> a=Article::Status.new("esquisse")
=> "draft"
>> a.is_draft?
=> true

The translated value is available via to_html:

>> Article::Status::PUBLISHED.to_html
=> "publiés"
>> Article::Status::PUBLISHED.to_html.html_safe?
=> true

Translations only work with named EnumString’s. The recommended way of naming the EnumString is to assign it to a constant, but if you do not wish to do this, you can supply the name in an option:

>> HoboFields::Types::EnumString.for('one', 'two', 'three', :name => "Count").inspect
=> "Count"

tableize will be called on your name to provide the translation key.

#

HoboFields::Types::RawHtmlString

    # no safety treatments are done by `to_html`.
    # even if `nasty.to_html` is actually unsafe, it is marked as html_safe.
    >> nasty = HoboFields::Types::RawHtmlString.new("p1<p>p2</p>p3<nasty>p4</nasty>p5&lt;script&gt;p6<script>p7</script>p8")
    >> nasty.to_html
    => "p1<p>p2</p>p3<nasty>p4</nasty>p5&lt;script&gt;p6<script>p7</script>p8"
    >> nasty.to_html.html_safe?
    => true

HoboFields::Types::RawMarkdownString

    # no safety treatments are done by `to_html`.
    # even if `markdown.to_html` is actually unsafe, it is marked as html_safe.
    >> markdown = HoboFields::Types::RawMarkdownString.new("<script>foo</script>")
    >> markdown.to_html.strip
    => "<script>foo</script>"
    >> markdown.to_html.html_safe?
    => true

Edit this page