5

I'm generating documentation with Yard but i can't find any example documentations for ruby on rails projects. I have found only short getting started tutorial, and some github projects on rubydoc.info, but they are not documented at all. please could somebody show me how to properly document controllers(with actions), models, routes of rails project

for instance i have such controller:

class ArticlesController < ApplicationController
  before_filter :authenticate_user!, except: [:show]
  before_filter :restrict_user, only: [:edit, :update]

  def index
    @articles = current_user.articles.sort_by_rating.
        paginate(:page => params[:page],
                 per_page: 5)
  end

  def new
    @user = User.find(params[:user_id])
    @article = @user.articles.build
  end

  def create
    @user = User.find(params[:user_id])
    @article = @user.articles.build(params[:article])

    if @article.save
      redirect_to  @article, notice: 'Article was successfully created.'
    else
      render action: "new"
    end
  end
end

And a user model:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable :recoverable
  devise :database_authenticatable, :registerable,
         :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :name, :email, :password, :password_confirmation, :remember_me
  # attr_accessible :title, :body

  validates_presence_of :name
  validates_uniqueness_of :name, :email, :case_sensitive => false

  has_many :articles, dependent: :destroy

  letsrate_rater
end
Aydar Omurbekov
  • 2,047
  • 4
  • 27
  • 53

2 Answers2

0

I know this question is old but I have created a plugin for attr_accessible with data types pulled from db/schema.rb. This plugin is based directly off of YARD::Handlers::Ruby::AttributeHandler:

require 'active_support/inflector'
class AttrAccessibleHandler < YARD::Handlers::Ruby::AttributeHandler
  include ActiveSupport::Inflector
  handles method_call(:attr_accessible)
  namespace_only


  process do
    return if statement.type == :var_ref || statement.type == :vcall
    read, write = true, true
    params = statement.parameters(false).dup
    hashify_object_types(underscore(namespace.name).pluralize)
    # Add all attributes
    validated_attribute_names(params).each do |name|
      namespace.attributes[scope][name] ||= SymbolHash[:read => nil, :write => nil] #Comment this out to see getter and setter methods

      # Show their methods as well
      {:read => name, :write => "#{name}="}.each do |type, meth|
          object_type = attribute_type(name)
          o = MethodObject.new(namespace, meth, scope)
          if type == :write
            o.parameters = [['value', nil]]
            src = "def #{meth}(value)"
            full_src = "#{src}\n  @#{name} = value\nend"
            doc = "Sets the attribute #{name}\n
                   @param [#{object_type}] value the value to set the attribute #{name} to."
          else
            src = "def #{meth}"
            full_src = "#{src}\n  @#{name}\nend"
            doc = "@return [#{object_type}] #{name}\nReturns the value of attribute #{name}"
          end

          o.source ||= full_src
          o.signature ||= src
          o.docstring = doc if o.docstring.blank?(false)
          register(o)

          # Regsiter the object explicitly
          namespace.attributes[scope][name][type] = o #Comment this out to see getter and setter methods
      end
    end
  end
  def hashify_object_types(table)
    table_section = ""
    inside = false
    File.open("db/schema.rb").each do |line|
      if line =~ /create_table "#{table}"/ || inside == true
        inside = true
        table_section << line.chomp
        break if line.chomp.strip == "end"
      end
    end
    @hash_table = convert_keys(Hash[table_section.scan(/t\.(\w+)\s+"(\w+)"/).map(&:reverse)])
  end
  def attribute_type(name)
    @hash_table[name] || "Object"
  end
  def convert_keys(h)
    h.each_with_object({}) do |(k,v),obj|
      obj[k] = v == "datetime" ? "DateTime" : v.capitalize
    end
  end
end

This makes the assumption that your plugin is in the root directory and you have a db/schema.rb file. It also will not handle classes where the table name is not an underscored pluralized string eg. BookAuthor #=> book_authors

engineersmnky
  • 25,495
  • 2
  • 36
  • 52
-2

I think something like this would work for you. But i am not 100% sure what your question is.

class ArticlesController < ApplicationController
  before_filter :authenticate_user!, except: [:show]

  def index
    @articles = current_user.articles.sort_by_rating.
        paginate(:page => params[:page],
                 per_page: 5)
  end

  def new
    #I think this is self explanatory. 
    @article = Article.new
  end

  def create
    #devise has the user id with current_user and rails will do the job for you. 
    @article = current_user.articles.build(article_params)

    if @article.save
      redirect_to  @article, notice: 'Article was successfully created.'
    else
      render action: "new"
    end
  end

end

The article model, would look something like this

class Article < ActiveRecord::Base

  #Remember Rails 4 does use attr_accessible on the model
  attr_accessible :title,  :body, :user_id

  #Article belongs to user
  belongs_to :user

  #Here we can validate presense of these fields.
  validates :title, :body, :user_id, :presence => true


end

The user model.

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable :recoverable
  devise :database_authenticatable, :registerable,
         :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :name, :email, :password, :password_confirmation, :remember_me
  # attr_accessible :title, :body

  validates_presence_of :name
  validates_uniqueness_of :name, :email, :case_sensitive => false

  #relationship with the article
  has_many :articles, dependent: :destroy

  letsrate_rater
end

If you are asking about how to document your project, Try Yard. http://yardoc.org/ or use RDoc you can turn it into browser-friendly HTML using the following built-in Rake task:

$ rake doc:app
Benjamin
  • 2,108
  • 2
  • 26
  • 46
  • you make me smile), it works fine, i just want to write documentation for this controller and model, and i don't know how to properly write it, maybe there are some rules for documentation, see more http://rubydoc.info/gems/yard/file/docs/GettingStarted.md – Aydar Omurbekov Oct 02 '13 at 06:38
  • Im glad it works. Do you mind accepting my answer? Are you asking how to use Yard? – Benjamin Oct 02 '13 at 06:49
  • What about documentation for the controller actions? Yes, I don't know how to use param and return tags for actions using Yard – Aydar Omurbekov Oct 02 '13 at 06:53