Generating Entity-Relationship Diagram for Ruby on Rails

Installation
Install graphviz (if not yet)
window http://www.graphviz.org/Download_windows.php
linux sudo apt-get install graphviz
osx brew install graphviz

Add the gem

In the project gemfile add

group :development do
  gem 'rails-erd'
end


Then execute cd PATH_OF_THE_PROJECT && bundle install

Using it
It's as simple as a bundle exec rake erd and it will generate a PDF file in the root of the app.

solve gem install ERROR on Windows with DevKit

หลังจากไม่ได้ลง windows ใหม่ปีกว่า…
พอลง ก็ต้องลงโปรแกรมนั่นนี้ และที่สำคัญ Ruby on Rails เครื่องมีทำมาหากิน

ลง ruby ตามปกติผ่านฉลุย ไม่มีอะไรเกิดขึ้น

แต่…. gem install rails(หรืออื่นๆ)

ERROR:  Error installing pg:
The ‘pg’ native gem requires installed build tools.

Please update your PATH to include build tools or download the DevKit
from ‘http://rubyinstaller.org/downloads’ and follow the instructions
at ‘http://github.com/oneclick/rubyinstaller/wiki/Development-Kit’

เหอๆ ยังดีที่บอกว่าให้ทำอะไรบ้าง

ก็ไปโหลด DevKit ตามที่เขาบอกที่ http://rubyinstaller.org/downloads

แล้วทำตามขั้นตอนที่ http://github.com/oneclick/rubyinstaller/wiki/Development-Kit

สรุปให้แบบง่ายๆ unzip DevKit ไว้ที่ไหนก็ได้(แต่ folder ห้ามมีช่องว่าง)
แล้วก็ไปที่ folder นั้น แล้ว run ไฟล์ dk.rb

ruby dk.rb init


กับ

ruby dk.rb install

เสร็จ

แล้วลอง gem install rails (หรืออื่นๆ) ผ่านฉลุยแน่นอน

Ruby on Rails Draw image by RMagick ...

require ‘RMagick’
include Magick
…
result = Magick::Image.new(1000, 725){ self.background_color = ‘#FFFFFF’ }
watermark = Magick::Image.read(“#{RAILS_ROOT}/public/logo/watermark.png”).first
logo = Magick::Image.read(“#{RAILS_ROOT}/public/logo/logo_xxx.png”).first
signature1 = Magick::Image.read(“#{RAILS_ROOT}/public/logo/sig1.png”).first
signature2 = Magick::Image.read(“#{RAILS_ROOT}/public/logo/sig2.png”).first
student_img = Magick::Image.read(“#{RAILS_ROOT}/public/images/gui/user_90x90.png”).first
result = result.composite(watermark, Magick::CenterGravity, 0, 0, Magick::OverCompositeOp)
result = result.composite(logo, Magick::NorthGravity, 0, 20, Magick::OverCompositeOp)
result = result.composite(signature1, Magick::NorthGravity, -250, 600, Magick::OverCompositeOp)
result = result.composite(signature2, Magick::NorthGravity, 250, 600, Magick::OverCompositeOp)
result = result.composite(student_img, Magick::NorthGravity, 345, 50, Magick::OverCompositeOp)
line1 = Draw.new
result.annotate(line1, 1000,30, 0, 200, “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”){
  line1.font = “#{RAILS_ROOT}/public/fonts/TH_Niramit_AS_Bold.ttf”
  line1.gravity = Magick::NorthGravity
  line1.pointsize = 18
  line1.fill = “#000000″
  line1.font_weight = Magick::BoldWeight
}
line2 = Draw.new
result.annotate(line2, 1000,30, 0, 240, “วุฒิบัตรฉบับนี้ให้ไว้เพื่อแสดงว่า”){
  line2.font = “#{RAILS_ROOT}/public/fonts/TH_Niramit_AS_Bold.ttf”
  line2.gravity = Magick::NorthGravity
  line2.pointsize = 18
  line2.fill = “#000000″
  line2.font_weight = Magick::BoldWeight
}
student_name = Draw.new
result.annotate(student_name, 1000,30, 0, 280,  “#{courses_student.prefix} #{courses_student.firstname}   #{courses_student.lastname}”){
  student_name.font = “#{RAILS_ROOT}/public/fonts/TH_Niramit_AS_Bold.ttf”
  student_name.gravity = Magick::NorthGravity
  student_name.pointsize = 18
  student_name.fill = “#000000″
  student_name.font_weight = Magick::BoldWeight
}
detail = Draw.new
result.annotate(detail, 1000,30, 0, 340, “ได้เข้าฝึกอบรม #{certificate_template.detail}”){
  detail.font = “#{RAILS_ROOT}/public/fonts/TH_Niramit_AS_Bold.ttf”
  detail.gravity = Magick::NorthGravity
  detail.pointsize = 18
  detail.fill = “#000000″
  detail.font_weight = Magick::BoldWeight
}
if courses_student.is_certified
  detail2 = Draw.new
  result.annotate(detail, 1000,30, 0, 370, “และผ่านเกณฑ์การประเมินผลสัมฤทธิ์การอบรม”){
    detail2.font = “#{RAILS_ROOT}/public/fonts/TH_Niramit_AS_Bold.ttf”
    detail2.gravity = Magick::NorthGravity
    detail2.pointsize = 18
    detail2.fill = “#000000″
    detail2.font_weight = Magick::BoldWeight
  }
end
line3 = Draw.new
result.annotate(line3, 1000,30, 0, 4100, “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”){
  line3.font = “#{RAILS_ROOT}/public/fonts/TH_Niramit_AS_Bold.ttf”
  line3.gravity = Magick::NorthGravity
  line3.pointsize = 18
  line3.fill = “#000000″
  line3.font_weight = Magick::BoldWeight
}
line4 = Draw.new
result.annotate(line4, 1000,30, 0, 440, “xxxxxxxxxxxxxxxxxxxxx”){
  line4.font = “#{RAILS_ROOT}/public/fonts/TH_Niramit_AS_Bold.ttf”
  line4.gravity = Magick::NorthGravity
  line4.pointsize = 18
  line4.fill = “#000000″
  line4.font_weight = Magick::BoldWeight
}
line5 = Draw.new
result.annotate(line5, 1000,30, 0, 470, “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx “){
  line5.font = “#{RAILS_ROOT}/public/fonts/TH_Niramit_AS_Bold.ttf”
  line5.gravity = Magick::NorthGravity
  line5.pointsize = 18
  line5.fill = “#000000″
  line5.font_weight = Magick::BoldWeight
}
line6 = Draw.new
result.annotate(line6, 1000,30, 0, 500, “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”){
  line6.font = “#{RAILS_ROOT}/public/fonts/TH_Niramit_AS_Bold.ttf”
  line6.gravity = Magick::NorthGravity
  line6.pointsize = 18
  line6.fill = “#000000″
  line6.font_weight = Magick::BoldWeight
}
thai_mon = ["", "มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม"  "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน",  "ธันวาคม"]
date = Draw.new
result.annotate(date, 1000,30, 0, 540, “ให้ไว้ ณ วันที่  #{Date.today.day} เดือน #{thai_mon[Date.today.mon]} พ.ศ.  #{Date.today.year + 543}”){
date.font = “#{RAILS_ROOT}/public/fonts/TH_Niramit_AS_Bold.ttf”
date.gravity = Magick::NorthGravity
date.pointsize = 18
date.fill = “#000000″
date.font_weight = Magick::BoldWeight
}
sig2_name = Draw.new
result.annotate(line6, 1000,30, 250, 668, “(xxxxxxxxxxxxxxxxxxxxxxxxxxxxx)”){
  sig2_name.font = “#{RAILS_ROOT}/public/fonts/TH_Niramit_AS_Bold.ttf”
  sig2_name.gravity = Magick::NorthGravity
  sig2_name.pointsize = 18
  sig2_name.fill = “#000000″
  sig2_name.font_weight = Magick::BoldWeight
}
sig2_desc = Draw.new
result.annotate(line6, 1000,30, 250, 688, “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”){
  sig2_desc.font = “#{RAILS_ROOT}/public/fonts/TH_Niramit_AS_Bold.ttf”
  sig2_desc.gravity = Magick::NorthGravity
  sig2_desc.pointsize = 18
  sig2_desc.fill = “#000000″
  sig2_desc.font_weight = Magick::BoldWeight
}
filename = “#{directory}/cert_#{@course.id}_#{courses_student.student_id}_#{courses_student.student_id}.jpg”
result.write(filename)

Using a proxy with open-uri

ทำโปรเจค EBMWiz  ตอนตั้ง server ไว้ที่ office ก็ใช้งานได้ปกตินี่นา

แต่ทำไมพอย้ายไป server ไปไว้ที่ใน มข. มันใช้ไม่ได้

สงสัยว่าอาจจะต้องใช้ proxy ก่อน

require 'open-uri'
url = 'http://www.pubmed.com/'

proxy_addr = 'http://home.kku.ac.th/proxy.pac:'
proxy_port = '3128'

page = open(url, :proxy => (proxy_addr + proxy_port))

Ruby Percent Syntax (Percent Functions)

I wanted to post a quick guide to the special ruby syntax for literals that utilize the % (percent) symbol. Most beginners guides to ruby leave out an explanation of these forms of literals, but many ruby coders use them. When someone encounters them for the first time it is almost impossible to figure out what they mean. (Try searching Google for “%w”)

Ruby has special syntax for making strings, arrays and system commands easier to write. They allow you to use different characters as delimiters so you can minimize escaping in your literals.

The syntax

The syntax for the % literals is a percent symbol (%) a letter which defines what kind of literal it is (Q, q, w, x, r) a delimiter,  the content, and the closing delimiter.

The delimiter can be any character, and is defined as whatever is immediately after the letter in the syntax. For example %Q!content! , the delimiter is the ! and it surrounds the content. There are special cases when the delimiter is { or (, the closing delimiter will be } or ) respectively.

%Q and %q (Percent Q): Strings

%Q!Some String of “Characters”! <==> ” Some String of \”Characters\” “

%Q is the equivalent to a double-quoted ruby string. #{expression} evaluation works just like in double-quoted strings, even if you use %Q{} as your delimiter!

You can also leave off the Q and it will have the same functionality. I recommend leaving the Q in to be more clear.

%q!Some String of “Characters”! <==> ‘Some String of Characters’

The %q is just like %Q, but acts the same as a single-quoted string. Whatever is inside the delimiters is returned as a string.

You can remember %Q is for strings because it acts like Quotes.

More info here: http://docs.huihoo.com/ruby/ruby-man-1.4/syntax.html#string

%W (Percent W): Arrays

%W(North South East West) <==> ["North", "South", "East", "West"]

%W (and %w) allow you to create an Array of strings without using quotes and commas.

The delimiter rules are the same as strings, but typically parentheses are used. The content inside the delimiters are split by white-space, and put into an array. This is great if you have a hard coded list of single word strings.

When using %W (capital W), it is evaluated as a double-quoted string. This allows you to use #{} to interpolate values. %w (lower-case w) will evaluate as a single quoted string.

You can remember %W is by thinking of it as a White-space divided Array.

More info here : http://docs.huihoo.com/ruby/ruby-man-1.4/syntax.html#array

%x (Percent x): System Execution

%x{ ls /usr/local } <==> `ls /usr/local`

%x allows you to call system commands, equivilent to wrapping the command in `s (grave accents). The benefit of the $x{} syntax is you don’t have to escape your accents in commands that use them.

You can remember to use X because it eXecutes a command.

More info here: http://docs.huihoo.com/ruby/ruby-man-1.4/syntax.html#command

%r (Percent r): Regular Expressions

%r{/usr/bin/} <==> /\/usr\/bin\//

%r is really handy for regular expressions that contain /s (forward slashes) which are the default delimiter for regular expressions and have to be escaped.

Remember to use %r with regular expressions.

More info here: http://docs.huihoo.com/ruby/ruby-man-1.4/syntax.html#regexp

I hope this information is helpful. Please leave a comment if this helped or if I left something out.

Tags: Percent Functions, Percent Literals, Ruby, Syntax

credit : http://jimhoskins.com/2008/10/07/ruby-percent-syntax-percent-functions/

Rails 4.1.0 - Nginx Bad Gateway with Passenger

I'm writing a little issue tracking application, and as it's a new app I'm using the new shiny Rails 4.1.0. However, whilst the application runs fine locally using Webrick I've been unable to get it working when deployed onto a live (staging) environment running Passenger and Nginx (using the Ubuntu package available via the Phusion Passenger site).

When deployed and configured, Nginx reports a 502 Bad Gateway exception. Digging throught the Nginx error log (in /var/log/nginx), the error becomes clear:

Exception RuntimeError in Rack application object (Missing secret_key_base for 'production' environment, set this value in config/secrets.yml)

Opening secrets.yml shows that there is no value for production:

development:
  secret_key_base: **not_for_prying_eyes**

test:
  secret_key_base: **not_for_prying_eyes**

# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>


You can either set an environment variable, or directly configure a value here (you can run rake secret to generate a key). Just make sure that if you do the latter, you've added secrets/yml to your .gitignore!

Modify div.fieldWithErrors from Rails forms

In a decision I have never understood, Rails forms by default add <div> ... </div> around any field in your form that has validation errors on submission. Which sucks when you end up with markup like this:

<div><label for="post_title">Title</label></div><br />
<div><input id="post_title" name="post[title]" size="30" type="text" value="" /></div>

At work we’ve had a hack in place for a while not that dug into ActionView and turned off this nonsense. We normally don’t go highlighting form fields with errors anyway. As it turns out though, that HTML is actually rendered by a proc you can set. By default it looks like this:

ActionView::Base.field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"fieldWithErrors\">#{html_tag}</div>" }

Just override this proc to return the tag only:

ActionView::Base.field_error_proc = proc {|html, instance| html }

In your environment.rb file, that would be:

config.action_view.field_error_proc = proc {|html, instance| html }

จาก :: http://d.strelau.net/post/163547069/remove-div-fieldwitherrors-from-rails-forms

ตัวอย่างที่ทำเอง เอาไว้ที่ controller

ActionView::Base.field_error_proc = proc {|html, instance| %{<span>#{html}<span></span></span>} }

Drowngrading rubygems

sudo gem update --system 1.5.3

*** แนะนำ ***

Ruby 1.9.x แนะนำ rubygems 1.7.2 or 1.6.2 Ruby 1.8.x แนะนำ rubygems 1.5.3

*** ใช้เมื่อไร ***

- start server ไม่ได้

 

bundle install --deployment

หาก Gemfile ใช้ gem ที่ยังไม่ใช่ .gem เช่น

   

gem 'prawn', git: 'https://github.com/prawnpdf/prawn', branch: 'master'


*** อย่าลืมลง git ด้วย ถ้า source เป็น git

   
http://code.google.com/p/msysgit/downloads/list


bundle install ก็ผ่านปกติ แต่...

   
Error message:
        https://github.com/prawnpdf/prawn (at master) is not checked out. Please run `bundle install` (Bundler::GitError)


แก้ไขด้วย

   
bundle install --deployment


paperclips fix : has an extension that does not match its contents

ระหว่างทำ gallery เจอ error message ว่า
has an extension that does not match its contents
แต่... บน ubuntu ไม่เป็น งงเบย เป็นเฉพาะ windows
สร้างไฟล์ config/initializers/paperclips.rb
require 'paperclip/media_type_spoof_detector'
module Paperclip
  class MediaTypeSpoofDetector
    def spoofed?
      false
    end
  end
end

ยังไม่จบ แก้ไฟล์ config/enviroments/development.rb (สำหรับ run แบบ development)
...
Paperclip.options[:command_path] = "C:/Program Files/ImageMagick-6.8.9-Q16/"
...

Fix Paperclip: “has an extension that does not match its content” error on windows

เพิ่มบรรทัดด้านล่าง config/environments/development.rb

Paperclip.options[:command_path] = "C:/Program Files/ImageMagick-6.8.9-Q16/"


เพิ่มไฟล์ config/initializers/paperclip.rb
require 'paperclip/media_type_spoof_detector'
module Paperclip
  class MediaTypeSpoofDetector
    def spoofed?
      false
    end
  end
end

prettyprint กับ bootstrap-wysiwyg DIY

ไม่มีอะไรมาก ใช้มุก replace

            <script>
                jQuery(function($) {
                    $('#article_body_editor').on('keyup keypress blur change', function() {
                        article_body_editor = $('#article_body_editor').html()
                            .replace(/\[prettyprint\]/g, '<pre class="prettyprint">')
                            .replace(/\[prettyprint linenums\]/g, '<pre class="prettyprint linenums">')
                            .replace(/\[\/prettyprint\]/g, '</pre>')
                            .replace(/\[code\]/g, '<code>')
                            .replace(/\[\/code\]/g, '</code>');
                        $('#article_body').val(article_body_editor);
                    });
                });
            </script>

Using MySQL with Rails 3 on Windows

gem mysql2 ไม่ support mysql 64 bits ???

ลง mysql connector 32 bits

    http://dev.mysql.com/downloads/connector/c/


แล้วก็ ...


    gem install mysql2 -- '--with-mysql-lib="C:\Program Files (x86)\MySQL\MySQL Connector C 6.1\lib" --with-mysql-include="C:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include"


แล้วก็ ...

copy libmysql.dll จาก C:\Program Files (x86)\MySQL\MySQL Connector C 6.1\lib ไปไว้ที่ C:\Ruby193\bin นะจ๊ะ

Using MySQL with Rails 3 on Windows

    Install railsinstaller -> www.railsinstaller.org (I installed it to c:\Rails)

    Install MySQL (I used MySQL 5.5) -> dev.mysql.com/downloads/installer/

    --- for mySQL installation ---

    If you dont already have these two files installed you might need them to get your MySQL going

    vcredist_x86.exe -> http://www.microsoft.com/download/en/details.aspx?id=5555 dotNetFx40_Full_x86_x64.exe -> http://www.microsoft.com/download/en/details.aspx?id=17718

    Use default install Developer Machine

    -MySQL Server Config-
    port: 3306
    windows service name: MySQL55
    mysql root pass: root (you can change this later)
    (username: root)
    -MySQL Server Config-

    --- for mySQL installation ---

    --- Install the mysql2 Gem ---

    Important: Do this with Git Bash Command Line(this was installed with railsinstaller) -> start/Git Bash

    gem install mysql2 -- '--with-mysql-lib="c:\Program Files\MySQL\MySQL Server 5.5\lib" --with-mysql-include="c:\Program Files\MySQL\MySQL Server 5.5\include"'

    Now the gem should have installed correctly

    Lastly copy the libmysql.dll file from
    C:\Program Files\MySQL\MySQL Server 5.5\lib
    to
    C:\Rails\Ruby1.9.2\bin

    --- Install the mysql2 Gem ---




http://stackoverflow.com/questions/3608287/error-installing-mysql2-failed-to-build-gem-native-extension

Can't install RMagick 0.0.0. Can't find MagickWand.h.

ลง imagemagick (32 bits) จาก http://www.imagemagick.org/script/binary-releases.php#windows
http://www.imagemagick.org/download/binaries/ImageMagick-6.8.9-6-Q16-x86-dll.exe

*** ตอนลง imagemagick ห้ามมีช่องว่าง ***

จากนั้น set path ให้ windows

เมื่อ gem install ใส่ option ด้วย เป็น path ของ imagemagick

gem install rmagick -- '--with-opt-dir="[path to ImageMagick]"'

เช่น
gem install rmagick -- '--with-opt-dir="C:\ImageMagick"'

RAILS MySQL ssh Tunnel

มีโทรศัพท์แจ้งมาว่า "แบท พี่เปลี่ยนวิธี connect mysql ให้ต้อง ssh tunnel นะ"
ตึ่งโป๊ะ!!! ทำไงๆๆๆ คืออะไร แค่เคยเห็นผ่านๆ แล้ว Ruby on Rails ทำไง

อันดับแรก
ssh -N -L 8888:127.0.0.1:3306 -f remote-user@remote-domain-or-ip

ใน database.yml ก็

 production:
  adapter: mysql2
  encoding: utf8
  host: 127.0.0.1
  port: 8888
  database: databasename
  username: remote-user
  password: password-remote-user


เสร็จ connect สำเร็จ ข้อมูลมา แต่ทำไมออกมาไม่เหมือนกัน
อ้าว!!! เปลี่ยนชื่อ database อีกก็ไม่บอก

Net::SMTPFatalError: 553 5.1.2 The address specified is not a valid RFC-5321 address.

โอ้ววว เมลไม่ออก ตั้งแต่วันอังคาร

Net::SMTPFatalError: 553 5.1.2 The address specified is not a valid RFC-5321 address. - gsmtp

จากเดิมใน xxx_mailer.rb
mail(from: "ibatt.in.th@gmail.com", to: "to@email.com", subject: 'สวัสดีมนุษย์')

แก้เป็น
mail(from: "I'm BATT <ibatt.in.th@gmail.com>", to: "to@email.com", subject: 'สวัสดีมนุษย์')

Prawn Font family

อยากใช้ font ไทย ใน prawn แล้วอยากใช้ inline format ด้วย

prawn คืออะไร plugin ruby เอาไว้เขียน pdf
inline format คืออะไร ก็แบบ ใส่ <b></b> แล้วได้ตัวหน้า ใส่ <i></i> ได้ตัวเอียง

ก็เพิ่ม font family สิครับ


    pdf = Prawn::Document.new :page_size => 'A4', :margin => [margin_top, margin_right, margin_bottom, margin_left]
    
    pdf.font_families.update("THSarabun" => {
      :normal => File.join("public", "fonts", "THSarabun.ttf"),
      :italic => File.join("public", "fonts", "THSarabunItalic.ttf"),
      :bold => File.join("public", "fonts", "THSarabunBold.ttf"),
      :bold_italic => File.join("public", "fonts", "THSarabunBoldItalic.ttf")
    })
   
    pdf.font "THSarabun", size: 14   
   
    pdf.text "แบบฟอร์ม", align: :center
    pdf.text "<b>1. ชื่อโครงการ</b> #{@project.name}", inline_format: true
    pdf.text "#{@project.code}"