Category Archives: Ruby

[Ruby] rtrim and ltrim function for ruby

ref. http://www.ruby-forum.com/topic/119319

<code>

class String
  def rtrim(char)
    dump.rtrim!(char)
  end

  def rtrim!(char)
    gsub!(/#{Regexp.escape(char)}+$/, '')
  end

  def ltrim(char)
    dump.ltrim!(char)
  end

  def ltrim!(char)
    gsub!(/^#{Regexp.escape(char)}+/, '')
  end
end

s = "aaaaaabacbccccc"
p s
s.rtrim!("c")
p s
s.ltrim!("b")
p s
s.ltrim!("a")
p s

</code>

[Ruby on Rails] escape pre code <, >


class Regexp
	def each_match(str)
	     	#start = 0
		text =""
	   	#while matchdata = self.match(str, start)
	   	while match_data = self.match(str)
	   		text << match_data.pre_match	
		     	yield text, match_data
		      	#start = matchdata.end(0)
		      	str = match_data.post_match
		end
		text << str
	end
end

module ApplicationHelper
# In Ruby 1.9, you can also associate a block with a call to match. If no match is found,
# the block is ignored, and match returns nil. If a match is found, however, the
# MatchData object is passed to the block, and the match method returns whatever the
# block returns.

	def escape_precode(stprivater)
		return  if str.empty?
		pattern = %r{(<pre\s*[^>]*>)(\s*)(<code\s*[^>]*>)?(.*?)(</code>)?(\s*)(</pre>)}im
		return pattern.each_match(str) do |text,match_data| 
			if match_data.length == 8 
				text << handle_match8(match_data)
			elsif match_data.length == 6
				text << thandle_match6(match_data)
			end
		end	
	end

	protected
	def handle_match6(match_data)
		#return  "" if match_data.nil? or match_data.length != 6
		rt = "#{match_data[1]}#{match_data[2]}"
		rt << match_data[3].gsub(/</,'<').gsub(/>/,'>')
		rt << "#{match_data[4]}#{match_data[5]}"
	end

	def handle_match8(match_data)
		rt = "#{match_data[1]}#{match_data[2]}#{match_data[3]}"
		rt << match_data[4].gsub(/</,'<').gsub(/>/,'>')
		#rt << begin match_data[4].gsub!(/</,'<').gsub!(/>/,'>'); rescue  => ex;ex.message; end
		rt << "#{match_data[5]}#{match_data[6]}#{match_data[7]}"
	end
end
	

text3 = <<code>

<div id="list">
  <div>
    <%= @commentable.title %>
  </div>
  <div style="line-height:2.2em">
    <%=sanitize escape_precode @commentable.body %>
  </div>

  <h3>Listing comments</h3>
  <% @root_comments.each do |root| %>
    <% Comment.each_with_level( root.self_and_descendants) do |comment, level| %>
        <%= ('<div class="prefix_1">' * level).html_safe %>
        <hr/><%= comment.id %>:<%= comment.parent_id %>
        <div style="line-height:2.2em"> <%= begin sanitize(escape_precode( comment.body)) rescue  comment.body  end%>
        </div>
      <div>  
        <spen><%= comment.created_at %></spen>
        <spen>by <%= comment.user.email %></spen>
         <spen><%= link_to 'Reply', post_comment_path(@commentable,comment) %></spen>
       <spen><%= link_to 'Edit', edit_post_comment_path(@commentable,comment) %></spen>
        <spen><%= link_to 'Destroy', post_comment_path(@commentable, comment), confirm: 'Are you sure?', method: :delete %></spen>
      </div>
     <%= ('</div>' * level).html_safe %> 
    <% end %>
  <% end %>

  <br />
  <h2>New Comment</h2>  
  <%= form_for [@commentable, Comment.new] do |f| %>  
    <div>  
        <%= f.label :body %> <br/> 
        <%= f.text_area :body, rows: 12, cols: 68  %>  
      </div>  
      <div><%= submit_tag "Add Comment" %>   <%= link_to t('Back'), you_posts_path %></div>  
   <% end %>  
 
</code></pre>
<pre>
<%= form_for(@post) do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
</pre>
EOT

include ApplicationHelper
puts Time.now
puts escape_precode(text3)
puts Time.now

[Ruby] 숫자를 한글로 변환하기


#--*-- coding:utf-8 --*--
#숫자를 한글로 변환하기
def number_string2(num)
	return '영' if num == 0
	phonemic =['','일','이','삼','사','오','육','칠','팔','구']
	unit = ['','','십','백','천','만','십만','백만','천만','억','십억','백억','천억','조','십조','백조']
	ret =''
	parts = num.to_s.chars.to_a
	p parts
	cnt = parts.length
	cnt.times do |i|
		#p part
		pt = phonemic[parts[i].to_i]
		#p pt
		#p phonemic[parts[i+1].to_i]
		pt += (pt.empty?)? '': (cnt > 4 && !phonemic[parts[i+1].to_i].empty?)? unit[cnt][0,1] : unit[cnt]
		ret += pt
		cnt -= 1
	end 
	return ret
end

def number_string(num)
	return '영' if num == 0
	phonemic =['','일','이','삼','사','오','육','칠','팔','구']
	unit = ['','','십','백','천','만','십만','백만','천만','억','십억','백억','천억','조','십조','백조']
	ret =''
	parts = num.to_s.chars.to_a
	p parts
	cnt = parts.length
	parts.each_with_index do |part, i|
		pt = phonemic[part.to_i]
		#p pt
		#p phonemic[parts[i+1].to_i]
		pt += (pt.empty?)? '': (cnt > 4 && !phonemic[parts[i+1].to_i].empty?)? unit[cnt][0,1] : unit[cnt]
		ret += pt
		cnt -= 1
	end
	return ret
end

puts Time.new
num = 920876123078900
puts number_string(num)
puts Time.new

[ruby on rails] rails 3 application.rb: invalid multibyte char (US-ASCII) (SyntaxError)

ref. http://stackoverflow.com/questions/4717717/invalid-multibyte-char-us-ascii-validating-a-new-user-with-regex-using-ruby

When using UTF-8 and Ruby 1.9 you’ll need to prefix your files by adding as the first line:

# encoding: UTF-8

This is a hint to the parser to make sure not to interpret things using the wrong character set. Ruby 1.8 was really lax about this and it could cause trouble.

RVM(Ruby Version Manager)을 Ubuntu 11.04에 설치

참조: http://beginrescueend.com/rvm/install/
http://www.christopherirish.com/2010/08/25/how-to-install-rvm-on-ubuntu-10-04/

$ sudo apt-get install  curl  git
# RVM 최신버전 설치
$ bash < <(curl -s https://rvm.beginrescueend.com/install/rvm)

#Load RVM into your shell sessions as a function
$ echo ‘[[ -s "$HOME/.rvm/scripts/rvm" ]] && . “$HOME/.rvm/scripts/rvm” #Load RVM function’ >> ~/.profile

#  Reload shell configuration & test
$ source .profile

# 설치와 설정이 정상적이면 ‘함수임’(‘rvm is a function’) 메시지가 표시됨
$ type rvm | head -1

# 운영체제의 의존성을 확인
$ rvm notes

———————————————–
# Ruby 설치에 필요한 패키지 설치
$ sudo aptitude install build-essential bison openssl libreadline5 libreadline-dev curl git-core zlib1g zlib1g-dev libssl-dev vim libsqlite3-0 libsqlite3-dev sqlite3 libreadline-dev libxml2-dev git-core subversion autoconf

# 알려진 ruby 목록을 표시
$ rvm list known
# MRI Rubies
[ruby-]1.8.6[-p420]
[ruby-]1.8.6-head
[ruby-]1.8.7[-p352]
[ruby-]1.8.7-head
[ruby-]1.9.1-p378
[ruby-]1.9.1[-p431]
[ruby-]1.9.1-head
[ruby-]1.9.2-p180
[ruby-]1.9.2[-p290]
[ruby-]1.9.2-head
[ruby-]1.9.3[-preview1]
[ruby-]1.9.3-head
ruby-head

# Ruby 1.9.2 설치
$ rvm install 1.9.2

# Ruby 버전 이용하기
$ rvm use 1.9.2

# 정상적 동작확인
$ ruby -v
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-linux]

$ rvm list
rvm rubies
=> ruby-1.9.2-p290 [ x86_64 ]
ruby-1.9.3-preview1 [ x86_64 ]