Camping And Og

Using camping with Og is pretty straightforward. This howto just gives you some code to start hacking with Og. More doc on Og usage is included in the rdoc and on http://oxyliquit.de

Preamble

Og is an ORM that works like AR except that the schema gets generated from the class structure and not vice-versa

gem install og

Example

%w(rubygems camping og).each { |lib| require lib }

Camping.goes :Blog

module Blog
    # called by camping on start
    def self.create
      Og.start  # starts Og, manage the classes, builds the DB if inexistent
      # Og.setup(:store => :sqlite, :name => 'data') # equivalent to Og.start (same defaults)
      Og.thread_safe = false  # this is needed to avoid thread locking problems
    end
end

module Blog::Models
    class Entry 
      attr_accessor :title, String    # starting with 0.40.0/0.41.0 og returned to the attr-* syntax: a datatype must be given per property to mark the property as an Og entity
      attr_accessor :body,  String    # type defined as String
      attr_accessor :reads, Fixnum    # type defined as Fixnum
    end
end
=begin
Alternatively, use the following class definition if you're getting errors 
concerning missing methods with the above prop_accessor.

module Blog::Models
    class Entry < Og::Entity
      property :title         #property is an alias for attr_accessor
      property :body
      property :reads, Fixnum
    end
end

=end

module Blog::Controllers
    class Index < R '/'
      def get
        @entries = Entry.find(:limit => 10) # looks pretty like AR isn't it ?
        render :list
      end
    end

    class Add
      def post
        e = Entry.new
        e.title = input.title
        e.body  = input.body
        e.save

        redirect Index
      end
    end

end

module Blog::Views

    def layout
      html do
        head do
          title "Blog"
        end
        body do
          h2 "Blog"
          self << yield
        end
      end
    end

    def list
      h1 "List"
      ul do
        for entry in @entries
          li do
            div entry.title
            div entry.body
          end
        end
      end

      form :action => R(Add), :method => :post do
        div { input :name => :title, :type => :text }
        div { textarea :name => :body }
        div { input :type => :submit }
      end
    end

end

Run the example

camping blog.rb