Code highlight in Ruby On Rails 3 Using CodeRay
First open your Gemfile and add
gem 'coderay'
and run bundle install
bundle install
Next you need to add a method any where you want best place would be ApplicationController
def coderay(text)
text.gsub(/<code( lang="(.+?)")?>(.+?)<\/code>/m) do
CodeRay.scan($3, $2).div(:css => :class)
end
end
Suppose you have controller Post and it's action show
app/controllers/posts_controller.rb
def show
@post = Post.find(params[:id])
@post.body = coderay(@post.body)
end
now in view file change following
app/views/posts/show.html.erb
<%= @post.body %>
To
<%= sanitize @post.body %>
Now you need a stylesheet that define color scheme for your code
span.af{/* attribute name fat */}
span.an{/* attribute name */}
span.av{/* attribute value */}
span.aw{/* attribute value fat */}
span.bi{/* bin */}
span.c{/* comment */}
span.ch{/* char */}
span.cl{/* class*/}
span.cr{/* colour */}
span.co{/* constant */}
span.cv{/* class variable */}
span.df{/* definition */}
span.di{/* directive */}
span.dl{/* delimeter */}
span.do{/* doc */}
span.ds{/* doc string */}
span.e{/* escape */}
span.er{/* error */}
span.ex{/* exception */}
span.fl{/* float */}
span.fu{/* function */}
span.gv{/* global variable */}
span.hx{/* hex */}
span.i{/* integer */}
span.ic{/* include */}
span.id{/* ident */}
span.il{/* inline */}
span.in{/* interpreted */}
span.iv{/* instance variable */}
span.k{/* content */}
span.ke{/* css attribute */}
span.kw{/* css selector */}
span.la{/* label */}
span.lv{/* local variable */}
span.mod{/* modifier */}
span.oc{/* oct */}
span.on{/* operator name */}
span.op{/* operator */}
span.pc{/* pre constant */}
span.pt{/* pre type */}
span.pd{/* predefined */}
span.pp{/* preprocessor */}
span.rx{/* reg exp */}
span.r{/* reserved */}
span.s{/* string */}
span.sh{/* shell */}
span.sp{/* space */}
span.sy{/* symbol */}
span.ta{/* tag */}
span.tf{/* tag fat */}
span.ts{/* tag special */}
span.ty{/* type */}
span.v{/* variable */}
span.vl{/* css value */}
span.xt{/* xml text */}