<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>-Flyぁ梦- &#187; ruby on rails</title>
	<atom:link href="http://blog.11034.org/category/coding/ruby-on-rails/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.11034.org</link>
	<description></description>
	<lastBuildDate>Sun, 22 Jun 2025 08:59:05 +0000</lastBuildDate>
	<language>zh-CN</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.2.38</generator>
	<item>
		<title>Liunx下搭建Rails和Nginx环境</title>
		<link>http://blog.11034.org/2015-08/rails_nginx.html</link>
		<comments>http://blog.11034.org/2015-08/rails_nginx.html#comments</comments>
		<pubDate>Wed, 12 Aug 2015 05:21:26 +0000</pubDate>
		<dc:creator><![CDATA[-Flyぁ梦-]]></dc:creator>
				<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[nginx]]></category>

		<guid isPermaLink="false">http://blog.11034.org/?p=2504</guid>
		<description><![CDATA[用rails开发轻量级web，效率最高！ 安装rvm http://www.rvm.io/ \curl -sS [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>用rails开发轻量级web，效率最高！</p>
<p><span id="more-2504"></span></p>
<h2>安装rvm</h2>
<p><code class="markdown_inline_code">http://www.rvm.io/</code></p>
<pre class="markdown_pre"><code>\curl -sSL https://get.rvm.io | bash -s stable

echo "source $HOME/.rvm/scripts/rvm" &gt;&gt; ~/.bash_profile

source /etc/profile

然后就可以在命令行中使用rvm命令了</code></pre>
<h2>安装ruby</h2>
<p>安装rvm后安装ruby下载缓慢，手动在ruby.taobao.org下载ruby-1.9.3，将安装包放在rvm/archives下即可</p>
<p><code class="markdown_inline_code">rvm install 1.9.3-p545</code> （如果不指定p版本，则不一定会使用安装包，而去下载网上最新版本）</p>
<p><code class="markdown_inline_code">which ruby</code> 可以找到当前版本ruby版本和位置</p>
<p>按照http://ruby.taobao.org/的方法，将gem的source改为<code class="markdown_inline_code">https://ruby.taobao.org/</code></p>
<p>这里要大大赞一下taobao，为国内开发者提供了便利，然后严重鄙视和谴责GFW</p>
<pre class="markdown_pre"><code>gem sources --remove https://rubygems.org/
gem sources -a https://ruby.taobao.org/
gem sources -l
*** CURRENT SOURCES ***

https://ruby.taobao.org
# 请确保只有 ruby.taobao.org</code></pre>
<h2>安装mysql</h2>
<p><code class="markdown_inline_code">apt-get install mysql-server</code></p>
<p><code class="markdown_inline_code">apt-get install libmysqlclient-dev</code></p>
<p><code class="markdown_inline_code">gem install mysql2 -v=0.2.24</code> <code class="markdown_inline_code">gem install activerecord-mysql2-adapter</code></p>
<h2>安装rails</h2>
<p><code class="markdown_inline_code">gem install rails -v=3.0.20</code> 3.2版本以上使用了很多新的东西，包括要安装nodejs等环境比较麻烦</p>
<p><code class="markdown_inline_code">rails new demo --skip-bundle</code></p>
<pre class="markdown_pre"><code>如果提示缺少必要gem的话，可以使用bundle自动安装
cd demo
bundle config mirror.https://rubygems.org https://ruby.taobao.org
bundle install</code></pre>
<p><code class="markdown_inline_code">rails server</code>或者<code class="markdown_inline_code">rails s</code> 即可启动自带的WEBrick web server</p>
<h2>rails连接mysql</h2>
<p>在mysql中新建数据库</p>
<p>修改<code class="markdown_inline_code">config/database.yml</code></p>
<p>将adapter类型修改为<code class="markdown_inline_code">mysql2</code></p>
<pre class="markdown_pre"><code>production:
adapter: mysql2
database: db_name
username: db_user
password: db_pawd
host: 127.0.0.1
encoding: utf8
socket: /var/run/mysqld/mysqld.sock</code></pre>
<p>修改demo/Gemfile，注释#gem &#8216;sqlite3&#8217;，添加<code class="markdown_inline_code">gem 'mysql2', '&lt; 0.3'</code></p>
<p>然后写一个最简单的migrate文件用以测试，执行<code class="markdown_inline_code">RAILS_ENV=production db:migrate</code></p>
<p>不成功的原因：<br />
若提示无法加载libmysqlclient.18.dylib，是因为/usr/lib下没有这个文件，作一个软链接即可，前提是找到本机mysql安装位置：<br />
<code class="markdown_inline_code">ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib</code></p>
<h2>安装pcre和nginx</h2>
<p>源码安装，将nginx包解压到/opt/nginx-x.x.x后，不要将/opt/nginx-x.x.x改名为/opt/nginx，因为/opt/nginx目录会在编译后自动生成。然后不要删除源码目录，安装Passenger还会用到。</p>
<p><code class="markdown_inline_code">这里不需要自己编译安装Nginx</code>，因为安装Passenger的时候会需要编译安装一次</p>
<p>安装PCRE：<code class="markdown_inline_code">apt-get install libpcre3 libpcre3-dev</code></p>
<pre class="markdown_pre"><code>若自己编译nginx，方法如下：
./configure --prefix='/opt/nginx' --with-http_stub_status_module --with-http_sub_module --with-md5='/usr/lib' --with-sha1='/usr/lib --with-http_gzip_static_module' --with-http_ssl_module --with-cc-opt=-Wno-error --with-http_secure_link_module
# 若是手动编译安装PCRE，则需要加上 --with-pcre=/opt/pcre-8.36
make
make install
然后/opt/nginx目录就出来啦，安装完毕</code></pre>
<h2>安装Passenger</h2>
<p>首先是<code class="markdown_inline_code">gem install passenger</code> ，</p>
<p>然后进到gem的Passenger/bin目录中（可能在/usr/local/rvm/gems/ruby-1.9.3-p551/gems/passenger-5.0.16/），执行<code class="markdown_inline_code">passenger-install-nginx-module</code>脚本，选择第二种自定义安装nginx（第一种自动下载、编译、安装nginx），通过命令行输入nginx源码目录即可，之后都默认。</p>
<p>最后按照安装Passenger完毕给予的提示，配置nginx的conf/nginx.conf。</p>
<pre class="markdown_pre"><code>http {
passenger_root /usr/local/rvm/gems/ruby-1.9.3-p551/gems/passenger-5.0.16;
passenger_ruby /usr/local/rvm/gems/ruby-1.9.3-p551/wrappers/ruby;

server {
listen 80;
server_name localhost;
passenger_enabled on;
rails_env production;

location / {
root rails_project/public;
}
}
}</code></pre>
<h4  class="related_post_title">看看 linux , MySQL , nginx</h4><ul class="related_post"><li>2016-09-09 -- <a target="_blank" href="http://blog.11034.org/2016-09/64bits_linux_arena_memory.html" title="64位Linux下Java进程堆外内存迷之64M问题">64位Linux下Java进程堆外内存迷之64M问题</a></li><li>2015-08-28 -- <a target="_blank" href="http://blog.11034.org/2015-08/tomcat_linux.html" title="Linux下搭建Tomcat环境">Linux下搭建Tomcat环境</a></li><li>2013-06-23 -- <a target="_blank" href="http://blog.11034.org/2013-06/shida.html" title="院版十大了，那就XYT一下~">院版十大了，那就XYT一下~</a></li><li>2011-03-15 -- <a target="_blank" href="http://blog.11034.org/2011-03/spring_hibernate_annotation.html" title="SpringMVC+Hibernate的一些配置">SpringMVC+Hibernate的一些配置</a></li></ul><h4 class="related_post_title">看看 ruby on rails </h4><ul class="related_post"><li>2015-04-09 -- <a target="_blank" href="http://blog.11034.org/2015-04/json_ascii.html" title="JSON中出现解析错误的原因之一：不可打印字符">JSON中出现解析错误的原因之一：不可打印字符</a></li><li>2014-12-21 -- <a target="_blank" href="http://blog.11034.org/2014-12/ruby_encoding.html" title="Ruby字符串的编码">Ruby字符串的编码</a></li><li>2014-10-25 -- <a target="_blank" href="http://blog.11034.org/2014-10/linux_timeout.html" title="linux的timeout处理wkhtmltopdf进程超时">linux的timeout处理wkhtmltopdf进程超时</a></li><li>2014-10-04 -- <a target="_blank" href="http://blog.11034.org/2014-10/rails-has_many.html" title="Rails中has_many等的原理">Rails中has_many等的原理</a></li><li>2014-07-28 -- <a target="_blank" href="http://blog.11034.org/2014-07/active_support_235.html" title="简析Rails：active_support 2.3.5">简析Rails：active_support 2.3.5</a></li>]]></content:encoded>
			<wfw:commentRss>http://blog.11034.org/2015-08/rails_nginx.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JSON中出现解析错误的原因之一：不可打印字符</title>
		<link>http://blog.11034.org/2015-04/json_ascii.html</link>
		<comments>http://blog.11034.org/2015-04/json_ascii.html#comments</comments>
		<pubDate>Thu, 09 Apr 2015 08:59:36 +0000</pubDate>
		<dc:creator><![CDATA[-Flyぁ梦-]]></dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://blog.11034.org/?p=2407</guid>
		<description><![CDATA[JSON规范规定，字符串需要用Unicode传输，而对于ASCII码中的前32个不可打印字符（第33个字符为空 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>JSON规范规定，字符串需要用Unicode传输，而对于ASCII码中的前32个不可打印字符（第33个字符为空格）应该转化为明文的转义模式，比如换行符0A：&#8221;\n&#8221;，出现在json中就应该是明文的\n，所以内部表示就应该是&#8221;\\n&#8221;。</p>
<p>所以假如一个json字符串中出现了01-1F这31个字符（00空字符倒是不会出现错误），json就会解析错误。</p>
<p><span id="more-2407"></span></p>
<p>Ruby on Rails中的to_json方法，默认并没有将这31个字符给正确转义为json格式，会引起错误。</p>
<p>用Rails的console举例：</p>
<div id="attachment_2408" style="width: 495px" class="wp-caption aligncenter"><img class="size-full wp-image-2408" alt="ASCII码转json测试" src="http://blog.11034.org/wp-content/uploads/2015/04/asc.png" width="485" height="268" /><p class="wp-caption-text">ASCII码转json测试</p></div>
<p>所以可能要手动去删除1-31号不可显示的ASCII码，除了\n\r\t之外，一般来说这些字符对于内容显示上不存在作用。</p>
<p>补充一点，ASCII表的最后一个字符127位为DEL (delete)，虽然可能也算不可打印字符，不过这个字符不会引起json解析错误。</p>
<p>附上ASCii码表：<a href="http://www.asciima.com/">http://www.asciima.com/</a></p>
<p>一种解决办法：对to_json解析后的字符串进行字符过滤</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="ruby" style="font-family:monospace;">    <span style="color:#9966CC; font-weight:bold;">def</span> to_json<span style="color:#006600; font-weight:bold;">&#40;</span>options = <span style="color:#0000FF; font-weight:bold;">nil</span><span style="color:#006600; font-weight:bold;">&#41;</span>
        json_str = <span style="color:#0066ff; font-weight:bold;">@data</span>.<span style="color:#9900CC;">to_json</span><span style="color:#006600; font-weight:bold;">&#40;</span>options<span style="color:#006600; font-weight:bold;">&#41;</span>
        bytes = <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#93;</span>
        json_str.<span style="color:#9900CC;">each_byte</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>c<span style="color:#006600; font-weight:bold;">|</span>
            <span style="color:#9966CC; font-weight:bold;">next</span> <span style="color:#9966CC; font-weight:bold;">if</span> c <span style="color:#006600; font-weight:bold;">&gt;</span>= <span style="color:#006666;">1</span> <span style="color:#006600; font-weight:bold;">&amp;&amp;</span> c <span style="color:#006600; font-weight:bold;">&lt;</span>= <span style="color:#006666;">31</span>
            bytes <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> c
        <span style="color:#9966CC; font-weight:bold;">end</span>
        <span style="color:#0000FF; font-weight:bold;">return</span> bytes.<span style="color:#9900CC;">pack</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'C*'</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<h4  class="related_post_title">随便看一看</h4><ul class="related_post"><li>2018-06-09 -- <a target="_blank" href="http://blog.11034.org/2018-06/bed.html" title="选择床和床垫的一些经验">选择床和床垫的一些经验</a></li><li>2012-02-10 -- <a target="_blank" href="http://blog.11034.org/2012-02/wp-sns-share_2-5.html" title="wp_sns_share更新2.5">wp_sns_share更新2.5</a></li><li>2010-08-22 -- <a target="_blank" href="http://blog.11034.org/2010-08/blog_new_life.html" title="blog新生">blog新生</a></li><li>2015-10-12 -- <a target="_blank" href="http://blog.11034.org/2015-10/kenting.html" title="我在垦丁晒太阳">我在垦丁晒太阳</a></li><li>2015-06-20 -- <a target="_blank" href="http://blog.11034.org/2015-06/huashan.html" title="战胜华山，一生平安">战胜华山，一生平安</a></li></ul><h4 class="related_post_title">看看 Javascript , ruby on rails </h4><ul class="related_post"><li>2015-08-12 -- <a target="_blank" href="http://blog.11034.org/2015-08/rails_nginx.html" title="Liunx下搭建Rails和Nginx环境">Liunx下搭建Rails和Nginx环境</a></li><li>2014-12-21 -- <a target="_blank" href="http://blog.11034.org/2014-12/ruby_encoding.html" title="Ruby字符串的编码">Ruby字符串的编码</a></li><li>2014-10-25 -- <a target="_blank" href="http://blog.11034.org/2014-10/linux_timeout.html" title="linux的timeout处理wkhtmltopdf进程超时">linux的timeout处理wkhtmltopdf进程超时</a></li><li>2014-10-04 -- <a target="_blank" href="http://blog.11034.org/2014-10/rails-has_many.html" title="Rails中has_many等的原理">Rails中has_many等的原理</a></li><li>2014-07-28 -- <a target="_blank" href="http://blog.11034.org/2014-07/active_support_235.html" title="简析Rails：active_support 2.3.5">简析Rails：active_support 2.3.5</a></li>]]></content:encoded>
			<wfw:commentRss>http://blog.11034.org/2015-04/json_ascii.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Ruby字符串的编码</title>
		<link>http://blog.11034.org/2014-12/ruby_encoding.html</link>
		<comments>http://blog.11034.org/2014-12/ruby_encoding.html#comments</comments>
		<pubDate>Sun, 21 Dec 2014 09:54:31 +0000</pubDate>
		<dc:creator><![CDATA[-Flyぁ梦-]]></dc:creator>
				<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://blog.11034.org/?p=2362</guid>
		<description><![CDATA[相比较于Java String的编码转换（先将String根据原字符集转化为字节数组，然后再用字节数组根据新字 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>相比较于Java String的编码转换（先将String根据原字符集转化为字节数组，然后再用字节数组根据新字符集拼装成新的字符串），Ruby的字符串编码转化省去了中间字节数组的过程，直接<code class="markdown_inline_code">string.encode(new_encoding)</code>即可。</p>
<p><span id="more-2362"></span></p>
<h2>字符串与字节串</h2>
<p>Ruby的字符串存储的都是字节，还有一个编码，根据这个编码对应的字符集来渲染字符。可以通过如下清除字符串的编码信息还原为裸的字节串：</p>
<pre class="markdown_pre"><code>str = '中'   #GBK编码
s1 = [str].pack('a*')   =&gt;   "\xD6\xD0"

str = '中'.encode('UTF-8')    #转化为UTF-8编码
s2 = [str].pack('a*')   =&gt;   "\xE4\xB8\xAD"

#Array.pack('a*')是用来向ASCII字符串结尾加入\0用的，所以会清除其他字符串的编码信息

s1.encoding.name =&gt; "ASCII-8BIT"</code></pre>
<p>现在得到的s1和s2字符串都是ASCII-8BIT的编码（或者说是没有带字符集的裸字节字符串），只要加上一个编码信息，就可以还原为GBK或者UTF-8的字符串，这种方式和Java也比较像了吧。</p>
<pre class="markdown_pre"><code>s1.force_encoding('GBK')          =&gt;     '中'
s2.force_encoding('UTF-8')         =&gt;     '中'</code></pre>
<p>Ruby中的字节数组，官方并没有给String直接的一个API来获取，但可以用过<code class="markdown_inline_code">str.unpack('c*') </code>或者<code class="markdown_inline_code">str.unpack('C*')</code>来获取，前者带符号位，后者不带符号位。</p>
<pre class="markdown_pre"><code>str = '中'   #GBK编码
[str].pack('c*')   =&gt;   [-42, -48]                  [str].pack('C*')   =&gt;  [214, 208]

str = '中'.encode('UTF-8')    #转化为UTF-8编码
[str].pack('c*')   =&gt;  [-28, -72, -83]              [str].pack('C*')   =&gt; [228, 184, 173]</code></pre>
<h2>UTF-8和Unicode</h2>
<p>不清除具体原因，在Ruby 1.9.3中，UTF-8字符串和Uniocde有一种特殊的自动转化方式（低于Ruby 1.9的版本，没有Unicode的支持），会自动进行转化，只要UTF-8字节串给加上了UTF-8的编码信息，字符串就自动转化为Unicode模式了。</p>
<pre class="markdown_pre"><code>"\xE4\xB8\xAD".force_encoding('UTF-8') == "\u4E2D"      =>     true</code></pre>
<p>将Unicode转化为UTF-8字符串：</p>
<pre class="markdown_pre"><code>"\u4E2D".each_byte {|b| print b.to_s(16)} =&gt; 'e4b8ad' #可见Unicode底层用UTF-8字节串存储

#字符串格式
"\u4E2D" # 底层就是UTF-8串

#双字节数字格式
0x4E2D（16进制） 或者 20013（10进制） =&gt; [0x4E2D].pack('U*') =&gt; "\u4E2D"</code></pre>
<p>&nbsp;</p>
<h4  class="related_post_title">随便看一看</h4><ul class="related_post"><li>2011-08-13 -- <a target="_blank" href="http://blog.11034.org/2011-08/lotus_of_west_lake.html" title="曲院风荷，婀娜多姿">曲院风荷，婀娜多姿</a></li><li>2023-06-20 -- <a target="_blank" href="http://blog.11034.org/2023-06/chongqing.html" title="23.6山城重庆游">23.6山城重庆游</a></li><li>2013-11-28 -- <a target="_blank" href="http://blog.11034.org/2013-11/lige.html" title="彩云之南-泸沽湖，里格村">彩云之南-泸沽湖，里格村</a></li><li>2010-08-26 -- <a target="_blank" href="http://blog.11034.org/2010-08/why_we_dont_have_good_email.html" title="为什么国内没有专业的Email服务商？">为什么国内没有专业的Email服务商？</a></li><li>2012-05-11 -- <a target="_blank" href="http://blog.11034.org/2012-05/a_perfect_world.html" title="A perfect world &#8211; 完美世界">A perfect world &#8211; 完美世界</a></li></ul><h4 class="related_post_title">看看 ruby on rails </h4><ul class="related_post"><li>2015-08-12 -- <a target="_blank" href="http://blog.11034.org/2015-08/rails_nginx.html" title="Liunx下搭建Rails和Nginx环境">Liunx下搭建Rails和Nginx环境</a></li><li>2015-04-09 -- <a target="_blank" href="http://blog.11034.org/2015-04/json_ascii.html" title="JSON中出现解析错误的原因之一：不可打印字符">JSON中出现解析错误的原因之一：不可打印字符</a></li><li>2014-10-25 -- <a target="_blank" href="http://blog.11034.org/2014-10/linux_timeout.html" title="linux的timeout处理wkhtmltopdf进程超时">linux的timeout处理wkhtmltopdf进程超时</a></li><li>2014-10-04 -- <a target="_blank" href="http://blog.11034.org/2014-10/rails-has_many.html" title="Rails中has_many等的原理">Rails中has_many等的原理</a></li><li>2014-07-28 -- <a target="_blank" href="http://blog.11034.org/2014-07/active_support_235.html" title="简析Rails：active_support 2.3.5">简析Rails：active_support 2.3.5</a></li>]]></content:encoded>
			<wfw:commentRss>http://blog.11034.org/2014-12/ruby_encoding.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>linux的timeout处理wkhtmltopdf进程超时</title>
		<link>http://blog.11034.org/2014-10/linux_timeout.html</link>
		<comments>http://blog.11034.org/2014-10/linux_timeout.html#comments</comments>
		<pubDate>Sat, 25 Oct 2014 14:16:17 +0000</pubDate>
		<dc:creator><![CDATA[-Flyぁ梦-]]></dc:creator>
				<category><![CDATA[Life in Coding]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[timeout]]></category>
		<category><![CDATA[wkhtmltopdf]]></category>

		<guid isPermaLink="false">http://blog.11034.org/?p=2313</guid>
		<description><![CDATA[rails程序中要调用一个系统命令，但是这个系统命令在某些时候可能会处理很久也得不到结果，就需要控制超时情况。 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>rails程序中要调用一个系统命令，但是这个系统命令在某些时候可能会处理很久也得不到结果，就需要控制超时情况。</p>
<p><span id="more-2313"></span></p>
<p>一开始用ruby的<code class="markdown_inline_code">Timeout.timeout</code>方法，首先这方法不是很好用，然后这个方法会开启一个新的线程处理block中的代码，然后当发生超时情况时，即抛出了Timeout::Error异常，是可以处理超时情况，但是那个被开启的线程无法管理，甚至会影响到rails的终端（不能正常Ctrl-C结束了），并且调用系统命令所开启的新进程并不会被中止仍然是继续在后台执行。</p>
<p>听了quark大牛的方法，尽量不要使用ruby的timeout方法，使用靠谱又简单的linux timeout命令。</p>
<pre class="markdown_pre"><code>timeout -k 1 10s cmd 即可

不指定-s，就默认超时后向进程发送TERM信号，即普通的kill

-k 1是指，当10s之后向超时进程发出TERM信号后，在又1秒之后向超时进程发出KILL信号</code></pre>
<p>在ruby中，用ret = `timeout`就可以直接调用系统命令，然后根据ret返回值进行判断是否超时。</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;wkhtmltopdf的分割线&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>PS：要用timeout处理的命令是wkhtmltopdf，将HTML页面转化为PDF的开源神器，但是在国内的环境中遇到HTML页面中有被墙了的页面的话，就是执行很久的时间（和浏览器一样），为了防止服务器处于假死状态，需要控制这个执行的时间。</p>
<p>然后顺便说下使用wkhtmltopdf过程中遇到的坑</p>
<ul>
<li>转化HTML中的图片，如果不成功的话，试着尝试使用<code class="markdown_inline_code">xvfb-run --server-args="-screen 0, 1280x1024x24" wkhtmltopdf</code></li>
<li>若转化过程中中文出了问题，检查linux中的微软雅黑（simsun.ttc）、宋体等字体文件是否存在<code class="markdown_inline_code">/usr/share/fonts/truetype</code>中</li>
<li>转化的HTML中必须要把那种全屏遮蔽的div、悬浮窗之类的删掉，大概因为PDF渲染颜色的原因，不仅转化需要超长时间而且打开PDF卡的要死</li>
</ul>
<h4  class="related_post_title">随便看一看</h4><ul class="related_post"><li>2013-10-31 -- <a target="_blank" href="http://blog.11034.org/2013-10/hulu.html" title="hulu校招">hulu校招</a></li><li>2010-11-28 -- <a target="_blank" href="http://blog.11034.org/2010-11/%e8%b4%a7%e5%b8%81%e6%88%98%e4%ba%89.html" title="货币战争">货币战争</a></li><li>2015-10-12 -- <a target="_blank" href="http://blog.11034.org/2015-10/hualien.html" title="我在花莲看日出">我在花莲看日出</a></li><li>2018-06-09 -- <a target="_blank" href="http://blog.11034.org/2018-06/bed.html" title="选择床和床垫的一些经验">选择床和床垫的一些经验</a></li><li>2011-06-11 -- <a target="_blank" href="http://blog.11034.org/2011-06/google_doodle_guitar.html" title="2011-6-9 Google Doodle之电子琴">2011-6-9 Google Doodle之电子琴</a></li></ul><h4 class="related_post_title">看看 Life in Coding , ruby on rails </h4><ul class="related_post"><li>2016-09-09 -- <a target="_blank" href="http://blog.11034.org/2016-09/jabber_and_xmpp.html" title="jabber和XMPP简述原理">jabber和XMPP简述原理</a></li><li>2015-08-12 -- <a target="_blank" href="http://blog.11034.org/2015-08/rails_nginx.html" title="Liunx下搭建Rails和Nginx环境">Liunx下搭建Rails和Nginx环境</a></li><li>2015-04-09 -- <a target="_blank" href="http://blog.11034.org/2015-04/json_ascii.html" title="JSON中出现解析错误的原因之一：不可打印字符">JSON中出现解析错误的原因之一：不可打印字符</a></li><li>2015-01-07 -- <a target="_blank" href="http://blog.11034.org/2015-01/prevent_db_duplicate.html" title="防止数据库数据重复的几种方法">防止数据库数据重复的几种方法</a></li><li>2014-12-21 -- <a target="_blank" href="http://blog.11034.org/2014-12/ruby_encoding.html" title="Ruby字符串的编码">Ruby字符串的编码</a></li>]]></content:encoded>
			<wfw:commentRss>http://blog.11034.org/2014-10/linux_timeout.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Rails中has_many等的原理</title>
		<link>http://blog.11034.org/2014-10/rails-has_many.html</link>
		<comments>http://blog.11034.org/2014-10/rails-has_many.html#comments</comments>
		<pubDate>Sat, 04 Oct 2014 15:42:56 +0000</pubDate>
		<dc:creator><![CDATA[-Flyぁ梦-]]></dc:creator>
				<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://blog.11034.org/?p=2308</guid>
		<description><![CDATA[刚接触rails的时候着实被has_many给惊到，这么厉害的功能，尤其是has_many的延迟加载，直到真正 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>刚接触rails的时候着实被has_many给惊到，这么厉害的功能，尤其是has_many的延迟加载，直到真正需要读取数据的时候才会进行SQL查询（person.posts.size，并不会执行select *到内存后再对Array执行size），但是用普通的调试方法怎么看has_many的结果是一个Array，比如.class方法，然后就觉得很神奇。</p>
<p><span id="more-2308"></span></p>
<p>看了源码之后，就了解has_many实现机制其实很简单，就是由一个代理类<code class="markdown_inline_code">ActiveRecord::Associations::HasManyAssociation</code>来实现的，真正的数据被封装在内部，真正需要用到数据的时候再去加载，这就是延迟加载；至于为什么看上去这么像Array或者说简直就是个Array是因为，<code class="markdown_inline_code">HasManyAssociation</code>算是一个白板类，删掉了从Object继承过来的大部分方法，包括.class方法，当你调用.class方法时就进入到了method_missing方法，然后就交给这个类内部的真正的数据结构Array去调用这个方法，自然表现出来就是一个Array了。所以要显示出这个类原来样貌，只要随意调用一个不存在的函数，比如person.posts.abcdefg()，就会提示HasManyAssociation没有这个方法了。</p>
<p>用法举例：</p>
<pre class="markdown_pre"><code>user.posts     // select * from

user.posts.size 或 user.posts.count  //select count(*) from

user.posts.length // select * from 后，再对Array取size；这个适用于需要先判断数量然后同时取数据（少量），省去count(*)这一条sql

user.posts &lt;&lt; Post.new 或 user.posts.create // insert into ...

user.posts.clear 或 user.posts.destroy_all  // delete from ...</code></pre>
<p><span style="color: #ff6600;"><strong>要尤其注意target的用法</strong></span>，因为<code class="markdown_inline_code">HasOneAssociation</code>本身就有target方法（用来获取Association对象本身），所以若对象本身又有target方法，则首先会调用Association对象的target方法。</p>
<pre class="markdown_pre"><code>class A
    has_one :relation, :class_name =&gt; 'B'
end

class B
    belong_to :target, :class_name =&gt; 'C'
end

a = A.find_by_id(1111)

a.relation =&gt; B的Association对象
p a.relation  =&gt;    B（先调用Association.method_missing方法，转而调用B.inspect方法）

a.relation.target =&gt; 只是B对象
p a.relation.target     =&gt;    B（直接调用B.inspect方法）

a.relation.target.target  =&gt;  C的Association对象
p a.relation.target.target       =&gt;    C</code></pre>
<p>这里选择打印调试则会出现比较奇怪的现象（p a.relation和p a.relation.target的结果是一样的，是因为p和puts调试，调用inpect和to_s方法，都是Association没有的，会通过method_missing转为调用对象本身的方法）</p>
<h4  class="related_post_title">随便看一看</h4><ul class="related_post"><li>2010-12-27 -- <a target="_blank" href="http://blog.11034.org/2010-12/scda_beijing.html" title="SCDA北京小聚">SCDA北京小聚</a></li><li>2014-07-07 -- <a target="_blank" href="http://blog.11034.org/2014-07/jay.html" title="杰伦，祝你幸福！">杰伦，祝你幸福！</a></li><li>2012-08-29 -- <a target="_blank" href="http://blog.11034.org/2012-08/the_tale_of_hachi.html" title="八公的故事 Hachi: A Dog&#8217;s Tale">八公的故事 Hachi: A Dog&#8217;s Tale</a></li><li>2012-10-12 -- <a target="_blank" href="http://blog.11034.org/2012-10/zoj_2891.html" title="zoj 2891">zoj 2891</a></li><li>2013-10-13 -- <a target="_blank" href="http://blog.11034.org/2013-10/tianmao_intern.html" title="天猫实习经历">天猫实习经历</a></li></ul><h4 class="related_post_title">看看 ruby on rails </h4><ul class="related_post"><li>2015-08-12 -- <a target="_blank" href="http://blog.11034.org/2015-08/rails_nginx.html" title="Liunx下搭建Rails和Nginx环境">Liunx下搭建Rails和Nginx环境</a></li><li>2015-04-09 -- <a target="_blank" href="http://blog.11034.org/2015-04/json_ascii.html" title="JSON中出现解析错误的原因之一：不可打印字符">JSON中出现解析错误的原因之一：不可打印字符</a></li><li>2014-12-21 -- <a target="_blank" href="http://blog.11034.org/2014-12/ruby_encoding.html" title="Ruby字符串的编码">Ruby字符串的编码</a></li><li>2014-10-25 -- <a target="_blank" href="http://blog.11034.org/2014-10/linux_timeout.html" title="linux的timeout处理wkhtmltopdf进程超时">linux的timeout处理wkhtmltopdf进程超时</a></li><li>2014-07-28 -- <a target="_blank" href="http://blog.11034.org/2014-07/active_support_235.html" title="简析Rails：active_support 2.3.5">简析Rails：active_support 2.3.5</a></li>]]></content:encoded>
			<wfw:commentRss>http://blog.11034.org/2014-10/rails-has_many.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>简析Rails：active_support 2.3.5</title>
		<link>http://blog.11034.org/2014-07/active_support_235.html</link>
		<comments>http://blog.11034.org/2014-07/active_support_235.html#comments</comments>
		<pubDate>Mon, 28 Jul 2014 13:02:26 +0000</pubDate>
		<dc:creator><![CDATA[-Flyぁ梦-]]></dc:creator>
				<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://blog.11034.org/?p=2272</guid>
		<description><![CDATA[项目中用到Rails2.3.5，就以此版本研究。和Rails本身相关的，大概有actionmailer（发邮件 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>项目中用到Rails2.3.5，就以此版本研究。和Rails本身相关的，大概有actionmailer（发邮件相关）、actionpack（HTTP和controller相关）、activerecord（ORM框架）、activeresource、activesupport（基础扩展库）。</p>
<p><span id="more-2272"></span></p>
<p>activesupport库算是一个基础扩展API库，主要分为两部分，一部分是可供选择的OOP形式的类和API，还有一部分是以Module形式存在的API以打开类的方式直接扩展进入Ruby源代码（即原有基础类）中。打开类扩展的API有一些应该被纳入Rurby源码，写惯Rails代码的脱离了activesupport再去写Ruby估计很不适应。</p>
<p>在po主本机上，库位于：`xx\Ruby193\lib\ruby\gems\1.9.1\gems\activesupport-2.3.5\lib`</p>
<h3>activesupport库的结构</h3>
<ul>
<li>activesupport.rb        已被废弃，require此文件会转require active_support.rb文件，并产生一个warning</li>
<li>active_support.rb      用来导入activesupport库中所有类和模块</li>
<li>active_support目录
<ul>
<li>core_ext目录                    基础扩展库
<ul>
<li>具体模块目录</li>
<li>模块目录导入文件</li>
<li>简单独立模块.rb</li>
</ul>
</li>
<li>vendor目录
<ul>
<li>具体模块目录</li>
</ul>
</li>
<li>具体功能目录&#8230;（如json）</li>
<li>功能导入文件.rb（如json.rb），用以导入同名具体功能目录下所有的文件</li>
<li>其他功能独立文件.rb（如base64.rb、ordered_hash.rb）</li>
</ul>
</li>
</ul>
<h3>activesupport导入流程</h3>
<ol>
<li>require active_support.rb</li>
<li>用autoload方法导入大部分独立类库和目录类库导入文件
<ol>
<li>目录类库导入文件，导入相应的目录下的文件，并作一些初始化工作</li>
</ol>
</li>
<li>require active_support/{vendor, core_ext, dependencies, json}
<ol>
<li>导入core_ext下所有rb文件，当rb文件为导入文件时，再导入core_ext下的目录文件</li>
<li>使用gem安装导入vender下的一些类库（builder、memcache-client、tzinfo、i18n）</li>
</ol>
</li>
</ol>
<p>active_support库的分层加载机制值得模仿学习，每一个子目录都有对应的一个导入rb文件。</p>
<h3>activesupport的core_ext基础库扩展</h3>
<p>按照功能类别排序划分。下面每个子目录下大概有2-10几个rb文件，都是对同一个模块或者类进行扩展，按照功能和意义的不同划分不同的类管理API。</p>
<ul>
<li>class目录</li>
<li>object目录</li>
<li>module目录</li>
<li>kernel目录</li>
</ul>
<ul>
<li>integer目录</li>
<li>numeric目录</li>
<li>bigdecimal目录</li>
<li>float目录</li>
</ul>
<ul>
<li>array目录</li>
<li>enumerable.rb</li>
<li>hash目录</li>
<li>range目录</li>
<li>string目录</li>
<li>proc.rb</li>
<li>symbol.rb</li>
</ul>
<ul>
<li>date目录</li>
<li>time目录</li>
<li>datetime目录</li>
</ul>
<ul>
<li>base64目录</li>
<li>file目录</li>
<li>cgi目录</li>
<li>process目录</li>
<li>pathname目录</li>
</ul>
<h4>Class、Object、Module、Kernel</h4>
<p>对Class的扩展：</p>
<ul>
<li>cattr_accessor :xxx，用来定义@@类变量，同时定义类方法和实例方法</li>
<li>read_inheritable_attribute、write_inheritable_attribute：用名为@inheritable_attributes的实例变量保存了一个hash，用来存储</li>
<li>class_inheritable_accessor :xxx，用类实例变量存储hash，实现同上</li>
<li>subclasses、remove_subclasses、remove_class</li>
</ul>
<p>对Object的扩展：</p>
<ul>
<li><code class="markdown_inline_code">blank?和present?</code></li>
<li>acts_like?(duck)：与具体模块中acts_like_duck?结合使用</li>
<li>with_options：调用可以传入hash键值的函数时，统一加入指定的键值对</li>
<li>tap：在调用链中用来遍历，本身什么也不干，一般用来输出调试</li>
<li>instance_values：将实例变量设置成hash返回</li>
<li>instance_variable_defined?：是否定义了某个实例变量</li>
<li>subclasses_of、extended_by、extend_with_included_modules_from：继承相关的API</li>
</ul>
<p>对Module的扩展：</p>
<ul>
<li>attr_internal :xxx和attr_internal_accessor :xxx，基本和attr_accessor一致，以@_xxx命名格式存储，不容易引起冲突（尤其在继承中）</li>
<li>mattr_accessor :xxx，定义@@xxx的读写方法。和Class的cattr_accessor的区别是，mattr用在module中，cattr用在Class中，混用可能导致错误</li>
<li>alias_method_chain(target, feature)：定义target_without_feature和target_with_feature函数，并将target alias 为feature。此函数在Rails源码中被用到很多</li>
<li>alias_attribute(new_name, old_name)：复制一套属性访问方法<strong><br />
</strong></li>
<li>included_in_classes：被included的Class集合</li>
</ul>
<p>对Kernel的扩展：</p>
<ul>
<li>daemonize：调用Process.daemon</li>
</ul>
<h4>Array、Enumerable、Hash、Range、String</h4>
<p>对Array的扩展：</p>
<ul>
<li>访问元素用的API（access.rb）：from(pos)、to(pos)、second、third、forty_two（这个API有点意思）</li>
<li>格式化输出的API（conversions.rb）：to_param、to_query、to_formatted_s代替to_s、to_xml</li>
<li>extract_options!（extract_options.rb）：取出函数参数中位于最后的hash</li>
<li>将元素分组的API（grouping.rb）：<code class="markdown_inline_code">in_groups_of(num)</code>每个组有num个元素、<code class="markdown_inline_code">in_groups(num)</code>分成num个组、split(value)按元素分组</li>
<li>rand(random_access.rb)：随机访问元素</li>
<li>wrap(wrapper.rb)：将其他对象包装成Array</li>
</ul>
<p>对Enumerable的扩展：</p>
<ul>
<li><code class="markdown_inline_code">index_by</code>：用元素的某个属性建立hash，最常见就是用id作为键</li>
<li><code class="markdown_inline_code">group_by</code>：用元素的某个属性建立元素为array的hash</li>
<li><code class="markdown_inline_code">each_with_object</code>：Ruby1.9中自带的方法</li>
<li>none?</li>
<li>sum?</li>
<li>many?</li>
</ul>
<p>from、to、index_by、group_by这几个函数太常用了，一开始不知道还自己写了一套通用的实现。</p>
<p>对Hash的扩展：</p>
<ul>
<li>格式化输入和输出的API(conversions.rb)：Hash.from_xml、to_xml、to_query</li>
<li>deep_merge和deep_merge!(deep_merge.rb)：当同一key两value都是Hash时递归式merge键值对</li>
<li>diff（diff.rb）：两个hash之间不同的键值对</li>
<li>except和except!（except.rb）：去除指定的key</li>
<li><code class="markdown_inline_code">slice</code>和slice!（slice.rb）：只留下指定的key</li>
<li>with_indifferent_access方法和HashWithIndifferentAccess类（indifferent_access.rb）：字符串和符号键无区别对待</li>
<li>reverse_merge和reverse_merge!（reverse_merge.rb）：反方向merge</li>
<li>格式化key的API（keys.rb）：stringify_keys、stringify_keys!和symbolize_keys、symbolize_keys!，前两个将所有key转化为字符串形式，后两个转为为符号</li>
</ul>
<p>对String的扩展：</p>
<p>文件太多，就列举一下API。</p>
<ul>
<li>访问类API：at(pos)用来解决Ruby1.8中返回int值的结构、<code class="markdown_inline_code">from(pos)、to(pos)</code>、first、last</li>
<li>转化为时间类API：<code class="markdown_inline_code">to_time(form = :utc)、to_date、to_datetime</code></li>
<li>squish和squish!：去掉字符串前后空格，并将内部的连续空格合并为1个</li>
<li>格式化字符串类API：使用外部的Inflector类实现
<ul>
<li>pluralize：复数形式</li>
<li>singularize：单数形式</li>
<li>camelize：驼峰形式</li>
<li>underscore：下划线形式</li>
<li>dasherize：中划线形式</li>
<li>demodulize：去除模块名之前的前导模块，得到最后的模块名</li>
<li>titleize：首字母大写</li>
<li>humanize：最佳阅读形式</li>
<li>classify：类名形式</li>
</ul>
</li>
<li>each_char：遍历每个字符</li>
<li>Ruby1.8字节串到字符串的转化API：<code class="markdown_inline_code">mb_chars、is_utf8?</code></li>
<li><code class="markdown_inline_code">starts_with?和end_with?</code></li>
<li>升级+和&lt;&lt;、add_with_safety、html_safe?：将+和&lt;&lt;升级用add_with_safety实现</li>
</ul>
<p>对Range的扩展：</p>
<ul>
<li>include?扩展即include_with_range?（include_range.rb）：升级为同时支持Range对象的include?判断</li>
<li>overlaps?（overlaps.rb）：判断是否覆盖</li>
</ul>
<h4>Proc和Symbol</h4>
<p>对Proc的扩展：只有一个bind函数，讲Proc绑定到一个object作为一个实例方法</p>
<p>对Symbol的扩展：只有一个<code class="markdown_inline_code">to_proc</code>函数（即对&amp;操作符的处理），配合起来index_by、group_by方法不要太给力。</p>
<p>hash_by_id = list.index_by(&amp;:id)            hash_group_by_type = list.group_by(&amp;:type)</p>
<h4>Integer、Numeric、Float</h4>
<p>很大程度配合Date、Time、DateTime模块。</p>
<p>对Integer的扩展：</p>
<ul>
<li>even?、odd?</li>
<li>ordinalize：给数字末尾加上序号串，1=&gt;1st，102=&gt;102nd</li>
<li>months、years：配合日期的加减或者直接打印，返回值是Duration对象</li>
</ul>
<p>对Numeric的扩展：</p>
<ul>
<li>bytes、kilobytes、megabytes、gigabytes、terabytes、petabytes、exabytes和所有的单数形式，节省计算各个1024</li>
<li>seconds、minutes、hours、days、weeks、fortnights：同Integer的months</li>
<li>ago(time)和untile(time)、since(time)和from_now(time)：前者time &#8211; self，后者time + self</li>
</ul>
<p>对Float的扩展：</p>
<ul>
<li>round_with_precision(precision = nil)：按照精度四舍五入</li>
<li>years、months</li>
</ul>
<h4>Date、Time和DateTime</h4>
<p>要结合core_ext同目录下的duration.rb中的Duration类实现。给这三个类增加的API都比较类似，就大致举例一些API和用法好了。</p>
<p>以下方法基本为Date和Time类共享：</p>
<ul>
<li>升级+和-为可以计算Duration类型的方法plus_with_duration(other)、minus_with_duration(other)</li>
<li>yesterday、tomorrow</li>
<li>past?、today?、future?</li>
<li>beginning_of_day、midnight、at_midnight、end_of_day、beginning_of_week、end_of_week、beginning_of_month、end_of_month、beginning_of_quarter、end_of_quarter、beginning_of_year、end_of_year</li>
<li>months_ago、months_since、years_ago、years_since</li>
<li>last_year、next_year、last_month、next_month、next_week</li>
<li>to_s(:db)：date对象直接生成%Y-%m-d形式，time对象生成%Y-%m-%d %H:%M:%S</li>
</ul>
<p>对Time加上时区的扩展：都是静态函数</p>
<ul>
<li>zone的读写</li>
<li>zone_default的读写</li>
<li>use_zone(time_zone)：修改时区</li>
<li>current</li>
</ul>
<h4>其他</h4>
<h3>activesupport的vendor</h3>
<p>现在只有builder、i18n、tzinfo、memcache-client四个模块</p>
<h3>activesupport的可选功能库</h3>
<p>按照个人觉得有用度排序，有些感觉没啥用的和暂时看不懂得没有列出来</p>
<ul>
<li>ordered_hash.rb和ordered_options.rb：保持插入顺序的Hash；OrderedOptions可以用hash.xxx = &#8216;xxx&#8217;的方式存储键值对（method_missing实现）</li>
<li>duration.rb：实现1.month.ago这样的时间跨度，用于对基础库Date和Time的扩展</li>
<li>callbacks.rb：define_callbacks :before_save, :after_save这样的钩子方法</li>
<li>rescuable.rb：捕获所有指定类型的异常，做统一处理</li>
<li>time_with_zone.rb：对Time类扩展时区功能</li>
<li>base64.rb：加密、解密</li>
<li>gzip.rb：用gzip算法压缩和读取string</li>
<li>json目录</li>
<li>multibyte目录：对Ruby1.8支持Unicode</li>
<li>cache目录：定了好几种存储方式，
<ul>
<li>drb_store</li>
<li>file_store</li>
<li>mem_cache_store</li>
<li>memory_store，就是个Hash</li>
<li>synchronized_memory_store，同步的memory_store</li>
<li>compressed_mem_cache_store</li>
</ul>
</li>
<li>locale目录</li>
<li>testing目录</li>
<li>values目录</li>
<li>xml_mini目录</li>
</ul>
<h3>其他学习到的地方</h3>
<ul>
<li>Ruby1.9+和Ruby1.8差别非常大，导致active_support代码中要各种判断Ruby版本
<ul>
<li>字符串用Unicode实现</li>
<li>Hash用OrderedHash实现</li>
<li>加入了BaseObject作为白板类</li>
</ul>
</li>
<li>Object的act_like?(xxx)方法和其他模块分别定义act_like_xxx?方法，配合实现类似Java的接口机制，一般单独写在behavior.rb文件的Behavior模块中</li>
</ul>
<h4  class="related_post_title">随便看一看</h4><ul class="related_post"><li>2013-05-20 -- <a target="_blank" href="http://blog.11034.org/2013-05/coyote.html" title="Tomcat的Connector：Coyote">Tomcat的Connector：Coyote</a></li><li>2020-08-02 -- <a target="_blank" href="http://blog.11034.org/2020-08/nanxun.html" title="第一次带娃自驾：南浔">第一次带娃自驾：南浔</a></li><li>2016-11-09 -- <a target="_blank" href="http://blog.11034.org/2016-11/bali_diving_spa.html" title="巴厘岛自由行-图兰奔深潜和豪华SPA">巴厘岛自由行-图兰奔深潜和豪华SPA</a></li><li>2010-11-28 -- <a target="_blank" href="http://blog.11034.org/2010-11/domain_change_to_stariy-org.html" title="域名更换">域名更换</a></li><li>2010-03-19 -- <a target="_blank" href="http://blog.11034.org/2010-03/web_development.html" title="Web 设计与开发资源大全">Web 设计与开发资源大全</a></li></ul><h4 class="related_post_title">看看 ruby on rails </h4><ul class="related_post"><li>2015-08-12 -- <a target="_blank" href="http://blog.11034.org/2015-08/rails_nginx.html" title="Liunx下搭建Rails和Nginx环境">Liunx下搭建Rails和Nginx环境</a></li><li>2015-04-09 -- <a target="_blank" href="http://blog.11034.org/2015-04/json_ascii.html" title="JSON中出现解析错误的原因之一：不可打印字符">JSON中出现解析错误的原因之一：不可打印字符</a></li><li>2014-12-21 -- <a target="_blank" href="http://blog.11034.org/2014-12/ruby_encoding.html" title="Ruby字符串的编码">Ruby字符串的编码</a></li><li>2014-10-25 -- <a target="_blank" href="http://blog.11034.org/2014-10/linux_timeout.html" title="linux的timeout处理wkhtmltopdf进程超时">linux的timeout处理wkhtmltopdf进程超时</a></li><li>2014-10-04 -- <a target="_blank" href="http://blog.11034.org/2014-10/rails-has_many.html" title="Rails中has_many等的原理">Rails中has_many等的原理</a></li>]]></content:encoded>
			<wfw:commentRss>http://blog.11034.org/2014-07/active_support_235.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>rails中慎用request.env</title>
		<link>http://blog.11034.org/2014-07/rails_request_env.html</link>
		<comments>http://blog.11034.org/2014-07/rails_request_env.html#comments</comments>
		<pubDate>Sat, 19 Jul 2014 03:52:41 +0000</pubDate>
		<dc:creator><![CDATA[-Flyぁ梦-]]></dc:creator>
				<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://blog.11034.org/?p=2270</guid>
		<description><![CDATA[项目中，为了获取URL中的path信息，就是域名后到?前的那一段字符串，随便百度了下，看到一篇文章里说用req [&#8230;]]]></description>
				<content:encoded><![CDATA[<p><span id="more-2270"></span>项目中，为了获取URL中的path信息，就是域名后到?前的那一段字符串，随便百度了下，看到一篇文章里说用request.env[&#8216;path&#8217;]可以获取，本地试了一下的确可以，在测试机上也OK，没想太多就部署上线了。</p>
<p>然后，然后就挂了，线上服务器request.env[&#8216;path&#8217;] = nil，一开始无法理解，后来得知web server是不一样的，打印了request.env这个hash，内容完全不一致，囧到了。然后发现request对象是直接有一套API的，直接request.path就好了，改为这个就所有web server通用了。</p>
<p>后来知道了，request.env只是简单的把类似CGI之前的环境变量参数封装起来，没有经过任何解析，这个是和web server的处理有很大的区别，即不跨环境的，要慎用。</p>
<h4  class="related_post_title">随便看一看</h4><ul class="related_post"><li>2013-06-14 -- <a target="_blank" href="http://blog.11034.org/2013-06/falcom_ys6.html" title="永远的伊苏6：纳比斯汀的方舟">永远的伊苏6：纳比斯汀的方舟</a></li><li>2013-02-26 -- <a target="_blank" href="http://blog.11034.org/2013-02/winter_travel.html" title="2013寒假辽宁天津游">2013寒假辽宁天津游</a></li><li>2011-07-21 -- <a target="_blank" href="http://blog.11034.org/2011-07/hk_90_movies.html" title="回味香港90年代电影，大爱王祖贤">回味香港90年代电影，大爱王祖贤</a></li><li>2010-07-26 -- <a target="_blank" href="http://blog.11034.org/2010-07/hongkong_travel.html" title="香港10日行，纪念第一次出境">香港10日行，纪念第一次出境</a></li><li>2012-11-06 -- <a target="_blank" href="http://blog.11034.org/2012-11/infernal_affairs.html" title="无间道">无间道</a></li></ul><h4 class="related_post_title">看看 ruby on rails </h4><ul class="related_post"><li>2015-08-12 -- <a target="_blank" href="http://blog.11034.org/2015-08/rails_nginx.html" title="Liunx下搭建Rails和Nginx环境">Liunx下搭建Rails和Nginx环境</a></li><li>2015-04-09 -- <a target="_blank" href="http://blog.11034.org/2015-04/json_ascii.html" title="JSON中出现解析错误的原因之一：不可打印字符">JSON中出现解析错误的原因之一：不可打印字符</a></li><li>2014-12-21 -- <a target="_blank" href="http://blog.11034.org/2014-12/ruby_encoding.html" title="Ruby字符串的编码">Ruby字符串的编码</a></li><li>2014-10-25 -- <a target="_blank" href="http://blog.11034.org/2014-10/linux_timeout.html" title="linux的timeout处理wkhtmltopdf进程超时">linux的timeout处理wkhtmltopdf进程超时</a></li><li>2014-10-04 -- <a target="_blank" href="http://blog.11034.org/2014-10/rails-has_many.html" title="Rails中has_many等的原理">Rails中has_many等的原理</a></li>]]></content:encoded>
			<wfw:commentRss>http://blog.11034.org/2014-07/rails_request_env.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ruby on rails</title>
		<link>http://blog.11034.org/2014-07/ruby_on_rails.html</link>
		<comments>http://blog.11034.org/2014-07/ruby_on_rails.html#comments</comments>
		<pubDate>Mon, 07 Jul 2014 13:51:26 +0000</pubDate>
		<dc:creator><![CDATA[-Flyぁ梦-]]></dc:creator>
				<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://blog.11034.org/?p=2252</guid>
		<description><![CDATA[工作需求，开始写ruby，因为基于web也就自然用上了rails。就这样开始接触ruby on rails，在 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>工作需求，开始写ruby，因为基于web也就自然用上了rails。就这样开始接触ruby on rails，在已有代码的基础上很快就能上手开发了。刚开始对ruby可能有各种吐槽，不过写习惯了之后真心觉得ruby语言本身挺不错的，比Python的语法舒服多了呢。</p>
<p><span id="more-2252"></span></p>
<h2>刚开始</h2>
<p>安装ruby真的够麻烦！装Java只要双击JDK然后配置环境变量即可；装Python只要双击python.msi然后配置环境变量即可；写这篇文章的时候我已经忘了怎么安装ruby了&#8230;只记得很麻烦，倒腾了很久！ <img src="http://blog.11034.org/wp-includes/images/smilies/icon_evil.gif" alt=":evil:" class="wp-smiley" style="height: 1em; max-height: 1em;" />  而且安装ruby的mysql驱动更是麻烦，win至今没装上，linux的也很麻烦！</p>
<p>ruby语言本身相比于其他脚本语言的确难很多，语法略晦涩难懂。</p>
<p>和Python类似，改了很多关键字，让熟悉静态语言的编程者不太习惯，尤其是elsif；next取代了continue；rescure取代了catch</p>
<p>ruby的对象在外部，没有“属性”这个概念，只有方法！只有在类内部才有属性和本地变量。惊呆了 <img src="http://blog.11034.org/wp-includes/images/smilies/icon_eek.gif" alt="8-O" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>ruby的拟态函数，看着就像一条命令，着实让新手期的我非常困惑，一个不带()的函数名加一个空格后的参数；完全找不到函数的定义，可能在某些module中，可能根本没有函数体是个用rails的has_many或者named_scope动态定义的函数&#8230;模块定义的函数，实例函数和静态函数也傻傻分不清楚。 <img src="http://blog.11034.org/wp-includes/images/smilies/icon_twisted.gif" alt=":twisted:" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>虽说Ruby和Java一样是纯OOP的语言，但是OOP的特性又很不一样，Ruby甚至不怎么推荐OOP的做法。</p>
<h2>渐渐地</h2>
<p>有点喜欢ruby了</p>
<ul>
<li> 函数名不带括号感觉很省事，导致写js的时候老忘了括号</li>
<li>类似 <code class="markdown_inline_code">return nil if params[:id] == nil</code>的一行代码，还可以 <code class="markdown_inline_code">render_error and return [ if xxx ]</code>，感觉太棒</li>
<li>遍历list/hash是那么方便</li>
<li>函数随意带block，自定义化程度非常高</li>
<li>rails是那么的强大，写web是那么的方便</li>
</ul>
<h2>rails和web</h2>
<p>写web，静态语言就Java（.Net不熟），脚本语言比较多：PHP、Python、Ruby，基本以这些为主流。Java不必说，太复杂开发效率低；PHP最灵活方便，但是没有一个好用强大的框架支持，功能复杂就显得力不从心；Python基于web写的不多，10年的时候用过Django，只能说一般般，现在不知道怎么样了，公司里也有同事在用Python写web，但感觉明显没有rails爽。</p>
<ul>
<li>rails的ORM强大到没有朋友</li>
<li>对ruby核心库的加强（ruby可以往原有类中直接加入API，不需要像Java中Apache类库的StringUtils那样用新的类）</li>
<li>view层面太方便的嵌套片段HTML；对ajax支持很好</li>
<li>debug方便，不仅方便地打印出所有SQL和模板加载，甚至有加载时间，优化起来很顺手</li>
</ul>
<p>深深的觉得，没有了rails，ruby真心没有太多闪光的地方&#8230;大概这也就是为什么ruby一直和rails绑定的关系吧</p>
<h2>ruby和rails的不足</h2>
<p>用到现在，受Java的影响，觉得ruby在以下几个方面用的还不是很灵活不习惯。很大程度上应该是自己对ruby和rails的了解还不够深入。</p>
<ul>
<li>继承体系：没有丰富的继承体系，OOP怎么体现优势？但是感觉rails中，写rails的Model时候，很难使用到完全自定义很灵活的继承体系。或者说Ruby的理念就不怎么喜欢用继承体系，更喜欢用Module的扩展甚至打开类技术。</li>
<li>数据结构库不丰富：只有内置的list/hash，对于常用的LinkedList、OrderedHashMap、HashSet等替代实现没有找到</li>
</ul>
<h4  class="related_post_title">看看 oop , PHP , Python</h4><ul class="related_post"><li>2014-09-10 -- <a target="_blank" href="http://blog.11034.org/2014-09/dotnet_csharp_excel.html" title="记C#和Excel开发">记C#和Excel开发</a></li><li>2012-12-06 -- <a target="_blank" href="http://blog.11034.org/2012-12/ac_automachine.html" title="一个OOP的AC自动机代码">一个OOP的AC自动机代码</a></li><li>2012-03-22 -- <a target="_blank" href="http://blog.11034.org/2012-03/java_util_collections.html" title="java.util中的集合类解析">java.util中的集合类解析</a></li><li>2010-11-17 -- <a target="_blank" href="http://blog.11034.org/2010-11/python2x_first_impression.html" title="Python2.x的第一印象">Python2.x的第一印象</a></li><li>2010-09-29 -- <a target="_blank" href="http://blog.11034.org/2010-09/wp-sns-share_add_tinyurl.html" title="wp-sns-share-1.2，增加tinyurl功能">wp-sns-share-1.2，增加tinyurl功能</a></li></ul><h4 class="related_post_title">看看 ruby on rails </h4><ul class="related_post"><li>2015-08-12 -- <a target="_blank" href="http://blog.11034.org/2015-08/rails_nginx.html" title="Liunx下搭建Rails和Nginx环境">Liunx下搭建Rails和Nginx环境</a></li><li>2015-04-09 -- <a target="_blank" href="http://blog.11034.org/2015-04/json_ascii.html" title="JSON中出现解析错误的原因之一：不可打印字符">JSON中出现解析错误的原因之一：不可打印字符</a></li><li>2014-12-21 -- <a target="_blank" href="http://blog.11034.org/2014-12/ruby_encoding.html" title="Ruby字符串的编码">Ruby字符串的编码</a></li><li>2014-10-25 -- <a target="_blank" href="http://blog.11034.org/2014-10/linux_timeout.html" title="linux的timeout处理wkhtmltopdf进程超时">linux的timeout处理wkhtmltopdf进程超时</a></li><li>2014-10-04 -- <a target="_blank" href="http://blog.11034.org/2014-10/rails-has_many.html" title="Rails中has_many等的原理">Rails中has_many等的原理</a></li>]]></content:encoded>
			<wfw:commentRss>http://blog.11034.org/2014-07/ruby_on_rails.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
