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.
Our test requires rails:
>> require 'rubygems'
>> require 'active_support'
>> require 'active_record'
>> require 'action_pack'
>> require 'action_view'
>> require 'action_controller'
ActiveRecord 2.3.2 doesn’t work very well without a connection, even though we don’t need it for this test:
>> mysql_adapter = defined?(JRUBY_VERSION) ? 'jdbcmysql' : 'mysql'
>> mysql_user = 'root'; mysql_password = ''
>> mysql_login = "-u #{mysql_user} --password='#{mysql_password}'"
>> mysql_database = "hobofields_doctest"
>> system "mysqladmin #{mysql_login} --force drop #{mysql_database} 2> /dev/null"
>> system("mysqladmin #{mysql_login} create #{mysql_database}") or raise "could not create database"
>> ActiveRecord::Base.establish_connection(:adapter => "mysql",
:database => mysql_database,
:host => "localhost", :user => mysql_user, :password => mysql_password)
Some load path manipulation you shouldn’t need:
>> $:.unshift File.join(File.expand_path(File.dirname(__FILE__)), '../../hobofields/lib')
>> $:.unshift File.join(File.expand_path(File.dirname(__FILE__)), '../../hobosupport/lib')
Finally we can require hobofields:
>> require 'hobosupport'
>> require 'hobofields'
>> HoboFields.enable
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
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::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 type="password">.
HoboFields::EmailAddress
Provides validation of correct email address format.
>> good = HoboFields::EmailAddress.new("foo@baa.com")
>> bad = HoboFields::EmailAddress.new("foo.baa.com")
>> !!good.valid?
=> true
>> good.validate
=> nil
>> !!bad.valid?
=> false
>> bad.validate
=> "is invalid"
HoboFields::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.
HoboFields::MarkdownString
HoboFields::MarkdownString provides a to_html that renders markdown syntax into html. It requires the bluecloth gem.
>> require 'bluecloth'
>> markdown = HoboFields::MarkdownString.new %(
This is a heading
=================
And text can be *emphasised*
)
>> markdown.to_html
>> markdown = HoboFields::MarkdownString.new "# This is a heading\n\nAnd text can be *emphasised*\n"
=>""
<h1>This is a heading</h1>
<p>And text can be <em>emphasised</em></p>
>>
HoboFields::TextileString
HoboFields::TextileString provides a to_html that renders markdown syntax into html. It requires the redcloth gem.
>> require 'redcloth'
>> textile = HoboFields::TextileString.new %(
Text can be _emphasised_
)
>> textile.to_html
=> "<p>Text can be <em>emphasised</em></p>"
>>
HoboFields::Text
HoboFields::Text provides a to_html method with HTML escaping and conversion of newlines to <br /> tags.
>> text = HoboFields::Text.new %(Tom & Jerry
Cat & Mouse)
>> text.to_html
=>
"Tom & Jerry<br />
<br />
Cat & Mouse"
>>
HoboFields::PasswordString
HoboFields::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 type='password'>
Enum Strings
HoboFields::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::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::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::EnumString:
>> a.is_a?(HoboFields::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::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::EnumString.for(:draft, :approved, :published)
fields do
status Article::Status
end
end
>> Article.attr_type :status
=> Article::Status
Translating EnumString’s
Named EnumString’s may be translated. Here is an example fr.yml:
fr:
article/statuses:
draft: "esquisse"
approved: "approuvé"
published: "publiés"
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"
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::EnumString.for('one', 'two', 'three', :name => "Count").inspect
=> "Count"
tableize will be called on your name to provide the translation key.
Cleanup
>> system "mysqladmin #{mysql_login} --force drop #{mysql_database} 2> /dev/null"