# HoboFields API In order for the API examples to run we need to load the rails generators of our testapp: {.hidden} doctest: prepare testapp environment doctest_require: 'prepare_testapp' {.hidden} ## Example Models Let's define some example models that we can use to demonstrate the API. With HoboFields we can use the 'hobo:model' generator like so: $ rails generate hobo:model advert title:string body:text contact_address:email_address >> Rails::Generators.invoke 'hobo:model', %w(advert title:string body:text contact_address:email_address) {.hidden} This will generate the test, fixture and a model file like this: class Advert < ActiveRecord::Base fields do title :string body :text contact_address :email_address end attr_accessible :title, :body, :contact_address end (Note: `:email_address` is an example of a "Rich Type" provided by HoboFields -- more on those later) The migration generator uses this information to create a migration. The following creates and runs the migration so we're ready to go. $ rails generate hobo:migration -n -m >> Rails::Generators.invoke 'hobo:migration', %w(-n -m) >> Rails::Generators.invoke 'hobo:migration', %w(-n -m) {.hidden} We're now ready to start demonstrating the API ## The Basics The main feature of HoboFields, aside from the migration generator, is the ability to declare rich types for your fields. For example, you can declare that a field is an email address, and the field will be automatically validated for correct email address syntax. ### Field Types Field values are returned as the type you specify. >> a = Advert.new :body => "This is the body" >> a.body.class => HoboFields::Types::Text This also works after a round-trip to the database >> a.save >> b = Advert.find(a.id) >> b.body.class => HoboFields::Types::Text HoboFields::Types::Text is a simple subclass of string. It's a "wrapper type", by which we mean you pass the underlying value to the constructor. >> t = HoboFields::Types::Text.new("hello") => "hello" >> t.class => HoboFields::Types::Text If you define your own rich types, they need to support a one argument constructor in the same way. Although the body of our advert is really just a string, it's very useful that it has a different type. For example, the view layer in Hobo Rapid would use this information to render a `