<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tony Hsu on Medium]]></title>
        <description><![CDATA[Stories by Tony Hsu on Medium]]></description>
        <link>https://medium.com/@tonyhsu23?source=rss-49a941ea8aaa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iahknOkmn8xoRtge3gZ8cg@2x.jpeg</url>
            <title>Stories by Tony Hsu on Medium</title>
            <link>https://medium.com/@tonyhsu23?source=rss-49a941ea8aaa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:02:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tonyhsu23/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AWS Lambda and API Gateway Version Control]]></title>
            <link>https://tonyhsu23.medium.com/aws-lambda-and-api-gateway-version-control-84b36c24dd91?source=rss-49a941ea8aaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/84b36c24dd91</guid>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Tony Hsu]]></dc:creator>
            <pubDate>Wed, 11 Nov 2020 08:44:10 GMT</pubDate>
            <atom:updated>2020-11-11T08:44:10.814Z</atom:updated>
            <content:encoded><![CDATA[<p>In order to do version control in Lambda, we all knew that we can do it with <strong>versions</strong> and <strong>aliases</strong>. What if I want to integrate the versioning with my API gateway <strong>stages</strong>. That means, in different stages, it will point to different versions I made of my functions. This gives me the ability to have environments like staging and production, which is great, we don’t want to mess them up to break my production codes. So let’s do it!</p><h3>Understanding the tools</h3><h4>Lambda Versions and Aliases</h4><p>Create a new version is easy, just click on “Actions” &gt; “Publish new version”. Version is named in increasing number. The first one is ‘1’, the second is ‘2’ and so on. Also, the code for any version is immutable, once you created a version, you can’t change the content. It’s like a snapshot of your function at that moment.</p><p>Then, it comes to aliases. An alias is a given name that points to one of your versions. You can change to a different version at any time you want. On top of that, there’s a feature that can split traffic to different versions. It is convenient when doing some testing.</p><h4>API Gateway Stages</h4><p>Stages are like separating APIs with different environments. With different stages, you will have different end-point of the API. When deploying APIs, you can easily choose between stages that you want them to be.</p><h3>Implementation</h3><h4>Lambda</h4><ol><li>Publish new version<br>Let’s say this is the first time we’re doing this, so we will get Version 1</li><li>Create aliases<br>Let’s create two aliases, stgand prod . And point them all to Version 1</li></ol><h4>API Gateway</h4><ol><li>Create stages<br>Create two stages called staging and production</li><li>Create stage variables<br>In each stage settings, click “Add Stage Variable” and give a name and its corresponding value.<br>For staging stage, create with a name like lambdaAlias. And the value is the actual alias name in your Lambda function that you want it to point to. In this case, the value will be stg. <br>For production, it will be Name: lambdaAlias, Value: prod.</li><li>Set the Lambda function name<br>Go to your API and click Integration Request. Then set the Lambda function like MY_FUNCTION:${stageVariables.lambdaAlias}.</li></ol><h3>Result</h3><p>At this point, if you send a request to the staging API, the lambda function that’ll be triggered will be MY_FUNCTION:stg.</p><p>Next time when you want to add new features to your function. You can do:</p><ol><li>Modify the code</li><li>Publish a new version</li><li>Make alias stg to have the new version of code</li><li>When it’s ready, you can switch alias prod to the new version of code</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84b36c24dd91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git rebase]]></title>
            <link>https://tonyhsu23.medium.com/git-rebase-b07f1c7a191a?source=rss-49a941ea8aaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/b07f1c7a191a</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[version-control]]></category>
            <dc:creator><![CDATA[Tony Hsu]]></dc:creator>
            <pubDate>Tue, 05 Jul 2016 07:41:48 GMT</pubDate>
            <atom:updated>2016-07-05T07:42:39.203Z</atom:updated>
            <content:encoded><![CDATA[<p>Last time, I used cherry-pick to solve my branch problems. This time, I found a new way to counter my recent problem. It is using git rebase.</p><p>According to git <a href="https://git-scm.com/docs/git-rebase">document</a>:</p><blockquote>git-rebase — Reapply commits on top of another base tip</blockquote><h4>My Local Repository</h4><p>This is my local repository looks like:</p><pre>master      -- A -- B -- C<br>                          \ <br>developing                 D -- E -- F</pre><p>I switched to anther branch(developing) to write a new feature.<br>After a while, my colleague pushed new commits to origin/master branch. So, after I pull it to my local repository, it became like this:</p><pre>master      -- A -- B -- C ------------- G<br>                          \ <br>developing                 D -- E -- F</pre><p>However, I wanted to push my works to remote repository based on the most recent master branch. The way to do it is to use git rebase.</p><pre># make sure I am on the branch which I want to rebase<br>git checkout developing</pre><pre>git rebase master</pre><p>After rebasing, it’ll looks like:</p><pre>master      -- A -- B -- C -- G<br>                               \ <br>developing                      D&#39; -- E&#39; -- F&#39;</pre><p>Branch D, E and F will be based on branch G. Also, D, E and F are still on branch developing. <br>Note that git will generate new commits for D, E and F.</p><p>Another interesting thing is that when the upstream branch already has changes you made, git will know and skip it.</p><p>For example,</p><pre>master      -- A -- B -- C ------------- G -- D&#39;<br>                          \ <br>developing                 D -- E -- F</pre><p>The upstream branch(master) contains the same changes branch D made. So when we do git rebase, it will skip commit D.</p><pre>master      -- A -- B -- C -- G -- D&#39;<br>                                    \ <br>developing                           E -- F</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b07f1c7a191a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[git cherry pick]]></title>
            <link>https://tonyhsu23.medium.com/git-cherry-pick-ad820c6de18c?source=rss-49a941ea8aaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad820c6de18c</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[version-control]]></category>
            <dc:creator><![CDATA[Tony Hsu]]></dc:creator>
            <pubDate>Fri, 03 Jun 2016 08:23:39 GMT</pubDate>
            <atom:updated>2016-06-03T08:23:39.480Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I’ve having trouble with git branches and commits. This is how I solve it after googled <a href="http://stackoverflow.com/questions/880957/pull-all-commits-from-a-branch-push-specified-commits-to-another/881014#881014">solutions</a>.</p><p>My had two branches, master and develop.</p><pre>master --- A <br>           \<br>develop     --- B --- C --- D</pre><p>First of all, in my local directory, I was on the <em>develop branch</em> with some changes made after <em>commit D</em>. I was going to switch to <em>branch master</em>. But it failed due to dirty working directory. The solution was to <strong>git stash</strong> them.</p><pre>// It will save those changed files else where<br>// (except for untracked files)<br>git stash</pre><pre>// To stash with untracked files you need to give it a flag<br>git stash -u</pre><pre>// To list all stash<br>git stash list</pre><pre>// To get your previous stash<br>git stash pop</pre><p>After doing git stash, I can checkout to <em>branch master</em>.</p><p>The thing I was trying to accomplish was merging <em>commit B </em>into <em>branch master. </em>The solution to this is cherry-pick.<br>I just gave it the SHA of <em>commit B</em>, and it added up <em>commit B</em> to <em>branch master</em>.</p><pre>git cherry-pick SHA</pre><p>Now, my network looks like this:</p><pre>master --- A ------------------ D&#39;<br>           \<br>develop     --- B --- C --- D</pre><p>Something you should notice is that <em>cherry-pick</em> will generate another SHA for the add-up commit. Therefore, branch D and D’ are not identical. The detail and downside of cherry-pick are well explained by the solutioin link above. Make sure you check it out before using this command.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad820c6de18c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Redis]]></title>
            <link>https://tonyhsu23.medium.com/learning-redis-19888ae947f1?source=rss-49a941ea8aaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/19888ae947f1</guid>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tony Hsu]]></dc:creator>
            <pubDate>Thu, 18 Feb 2016 06:50:58 GMT</pubDate>
            <atom:updated>2016-02-18T06:50:58.967Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the first time I play with Redis. I’ve heard of it, but never used it before. So I think it’s a good idea to jot these basic things down in my blog. I followed the steps of the official <a href="http://try.redis.io/">Try Redis Tutorial</a>. Since it is an interactive tutorial, my thought was to write these things down so that it’ll be easier for me to review them again instead of jumping around the tutorial.</p><p>Redis is a key-value store, also known as a NoSQL database. In other words, I can get any value want to retrieve by its key. Here&#39;s how to set values.</p><pre>SET myname &quot;tony&quot;<br># Here myname is the key, &quot;tony&quot; is the value</pre><pre>GET myname <br># return &quot;tony&quot;</pre><h4>Increment and Deletion</h4><p>SETNX is <em>Set-if-not-exist</em><br>INCR is <em>increment</em> a number stored at a given key<br>DEL is <em>delete</em></p><pre>SET whatever 10<br>INCR whatever # return 11<br>INCR whatever # return 12<br>DEL whatever<br>INCR whatever # return 1</pre><p>Note that even a key is nil, it still can increase its number. See above that I deleted the whatever key, it should be nil by than. However, I can still INCR after deletion, and it returns 1.</p><h4>Expiration</h4><p>You can set the time of existence of a key.<br>EXPIRE - set the time<br>TTL - time until deletion ( in seconds )</p><pre>SET resource &quot;demo&quot;</pre><pre>EXPIRE resource 120 <br># delete it after 120 sec.</pre><pre>TTL resource <br># return remaining seconds</pre><p>If TTL returns</p><ul><li>-2 means the key does&#39;t exist</li><li>-1 means it will never expire</li></ul><p><strong>Note that if you set a key, its TTL will be reset.</strong></p><h4>List</h4><p>There are several commands for lists.<br>RPUSH, LPUSH, LLEN, LRANGE, LPOP, RPOP</p><ol><li>RPUSH, LPUSH</li></ol><p>I believe the &#39;R&#39; and &#39;L&#39; at the beginning of the command means Right and Left (or list) respectively. As a result, RPUSH <em>push </em>a value at <em>the right side</em> (<em>at the end</em>) of the list. And, LPUSH <em>push </em>a value at <em>the left side</em> (<em>at the beginning</em>) of the list.</p><pre>RPUSH friends &quot;Alice&quot;<br>RPUSH friends &quot;Bob&quot;<br>LPUSH friends &quot;Sam&quot;</pre><pre># the list should looks like this<br># &quot;Sam&quot;, &quot;Alice&quot;, &quot;Bob&quot;</pre><p>2. LRANGE</p><p>It returns a subset of the list according to the element you give in the command. <br>First, is the parameter you want to get.<br>Second, is the range of indexes you want to get.</p><pre>LRANGE friends 0 1<br># retrieve from 0~1<br># &quot;Sam&quot;, &quot;Alice&quot;</pre><pre>LRANGE friends 1 2<br># retrieve from 1~2<br># &quot;Alice&quot;, &quot;Bob&quot;</pre><pre>LRANGE friends 0 -1<br># -1 means retrieve util the end of the list<br># &quot;Sam&quot;, &quot;Alice&quot;, &quot;Bob&quot;</pre><p>3. LLEN, LPOP, RPOP</p><ul><li>LLEN returns the <em>length </em>if the list.</li><li>LPOP pops(removes) the first element.</li><li>RPOP pops(removes) the last element.</li></ul><h4>Set</h4><p>Set is different from List. Lists have a specific order, which is first, second or last. But sets do not have orders. Also, every element in a set is <strong>unique</strong>, it does not appear second time in the same set.</p><ol><li>SADD, SREM</li></ol><p>It adds and removes a value from a set.</p><pre>SADD starwars &quot;Luke&quot;<br>SADD starwars &quot;Vader&quot;<br>SADD starwars &quot;Han&quot;</pre><pre>SREM starwars &quot;Han&quot;</pre><p>2. SISMEMBER, SMEMBER, SUNION</p><pre>SISMEMBER starwars &quot;Luke&quot;<br># return 1 (true, exist)</pre><pre>SISMEMBER starwars &quot;Han&quot;<br># return 0 (false, not exist)</pre><pre>SMEMBERS starwars<br># return all members in the set<br># &quot;Luke&quot;, &quot;Vader&quot;</pre><pre>----------------------------------</pre><pre># SUNION<br># combines two or more sets<br># returns the list of all elements</pre><pre>SADD empire &quot;stormtroopers&quot;<br>SADD empire &quot;Vader&quot;</pre><pre>SUNION empire starwars<br># &quot;Luke&quot;, &quot;Vader&quot;, &quot;Stormtroopers&quot;</pre><h4>Sorted Sets</h4><p>A sorted set is similar to a set except that it has an <strong>associated score</strong>. It is used to sort a the elements in the set.</p><pre>ZADD hackers 1940 &quot;Alan Kay&quot;<br>ZADD hackers 1906 &quot;Grace Hopper&quot;<br>ZADD hackers 1953 &quot;Richard Stallman&quot;<br>ZADD hackers 1965 &quot;Yukihiro Matsumoto&quot;<br>ZADD hackers 1916 &quot;Claude Shannon&quot;<br>ZADD hackers 1969 &quot;Linus Torvalds&quot;<br>ZADD hackers 1957 &quot;Sophie Wilson&quot;<br>ZADD hackers 1912 &quot;Alan Turing&quot;<br># the numbers are the associated score<br># which are the year they were born</pre><pre>ZRANGE hackers 0 2<br># &quot;Grace Hopper&quot;, &quot;Alan Turing&quot;, &quot;Claude Shannon&quot;</pre><h4>Hash</h4><p>Set hashes</p><pre>HSET user:1000 name &quot;Tony&quot;<br>HSET user:1000 email&quot;tony@example.com&quot;<br>HSET user:1000 password &quot;pass123&quot;</pre><pre>HGETALL user:1000<br># get all data</pre><pre>HMSET user:1001 name &quot;Alex&quot; email &quot;alex@example.com&quot; password &quot;aLeX&quot;<br># set multiple fields</pre><pre>HGET user:1001 name<br># return &quot;Alex&quot;</pre><p>Numeral hashes can also be increased</p><pre>HSET user:1000 visits 10<br>HINCRBY user:1000 visits 1 # return 11<br>HINCRBY user:1000 visits 10 # return 21<br>HDEL user:1000 visits<br>HINCRBY user:1000 visits 1 # return 1</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19888ae947f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reset Database on Heroku]]></title>
            <link>https://tonyhsu23.medium.com/reset-database-on-heroku-6adf6979b7fb?source=rss-49a941ea8aaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/6adf6979b7fb</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[heroku]]></category>
            <dc:creator><![CDATA[Tony Hsu]]></dc:creator>
            <pubDate>Mon, 28 Dec 2015 09:42:35 GMT</pubDate>
            <atom:updated>2015-12-28T09:42:35.310Z</atom:updated>
            <content:encoded><![CDATA[<p>It happened one day that I need to reset the database of my heroku app. Usually, I run 3 commands on my terminal to reset databases when developing. they are</p><pre>rake db:drop<br>rake db:create<br>rake db:migrate</pre><p>First drop the database, then create it again. Finally, you can run all the migrations.</p><p>However, <a href="https://devcenter.heroku.com/articles/rake#limitations">Heroku doesn&#39;t support all the rake command</a>. One of them is resetting the database, which was what I wanted to do. The solution is to run another command</p><pre>heroku pg:reset</pre><p>instead of</p><pre>rake db:reset</pre><p>Also, I looked up what <strong>db:reset</strong> does. It runs <strong>db:drop</strong>, then <strong>db:setup</strong>. <a href="http://stackoverflow.com/questions/10301794/difference-between-rake-dbmigrate-dbreset-and-dbschemaload">Here&#39;s the reference for you</a>.</p><p>But after running the reset command, the terminal ask for the <strong>DATABASE_URL</strong> of my app. What you need to do is put the exact DATABASE_URL string at the end of the reset command like this (<a href="http://stackoverflow.com/questions/14141803/heroku-postgresql-database-name">read details here</a>)</p><pre>heroku pg:reset DATABASE_URL</pre><p>That&#39;s it. Database is dropped. There&#39;s two more command to run, which is <strong>db:create</strong> and <strong>db:migrate</strong>.</p><pre>heroku run rake db:create<br>heroku run rake db:migrate</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6adf6979b7fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hidding data from Github and Heroku]]></title>
            <link>https://tonyhsu23.medium.com/hidding-data-from-github-and-heroku-65d5f58fb6b4?source=rss-49a941ea8aaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/65d5f58fb6b4</guid>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Tony Hsu]]></dc:creator>
            <pubDate>Thu, 24 Dec 2015 10:29:24 GMT</pubDate>
            <atom:updated>2015-12-24T10:29:24.369Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m using dropbox API to retrieve and store some photos on my rails app. Dropbox must give me API keys, secrets, tokens to get access to my own app. However, these data will be exposed if I simply store them in config files. The wonderful thing about rails is that we always have gems to look for. <a href="https://github.com/laserlemon/figaro"><strong>Figaro</strong></a> is the gem I’m using.</p><p>By following the document, the first step is installing the gem.</p><pre># add figaro in your gemfile<br>gem &quot;figaro&quot; </pre><pre># run bundle install</pre><p>After that, generate Figaro files by running</p><pre>$ bundle exec figaro install</pre><p>Figaro generates</p><ol><li>an <strong>application.yml</strong> file. (config/application.yml)</li><li>ignore <em>application.yml</em> file in github repository, which writes in <strong>.gitignore</strong></li></ol><p>Then, add your API keys, tokens and any other secrets you don’t want people to see.</p><p>For example,</p><pre># config/application.yml</pre><pre>APP_KEY: “4nr93dfsg4kj3e9g&quot;</pre><pre>APP_SECRET: “3859sjfin39fk3sdk4”</pre><pre>ACCESS_TOKEN: “5n39fn38gj3js&quot;</pre><p>Also, add these variables in the initializer you’re using. For me, I’m using dropbox API in <a href="https://github.com/robin850/carrierwave-dropbox">Carrierwave</a> gem</p><pre># config/initializers/carrierwave.rb</pre><pre>CarrierWave.configure do |config|<br>  config.dropbox_app_key = ENV[“APP_KEY”]<br>  config.dropbox_app_secret = ENV[“APP_SECRET”]<br>  config.dropbox_access_token = ENV[“ACCESS_TOKEN”]<br>  ..........<br>end</pre><p>Finally, we can deploy our app to Heroku.<br>After deploying the app, run this command to set your configuration.</p><pre>$ figaro heroku:set -e production</pre><h3>DONE!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65d5f58fb6b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails: Having Trouble With Turbolinks]]></title>
            <link>https://tonyhsu23.medium.com/rails-having-trouble-with-turbolinks-56b9204902d?source=rss-49a941ea8aaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/56b9204902d</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Tony Hsu]]></dc:creator>
            <pubDate>Wed, 16 Dec 2015 13:40:13 GMT</pubDate>
            <atom:updated>2015-12-17T14:01:45.714Z</atom:updated>
            <content:encoded><![CDATA[<p>Every time I create a rails app, I didn’t write any options in my terminal. I simply create them with basic command:</p><pre>rails new project</pre><p>Therefore, every default gems are included in my projects.</p><p>Recently, I’m working on <a href="https://github.com/galetahub/ckeditor">Ckeditor</a>. It is really straightforward. I didn’t have much trouble building it. However, I found out that <strong>I have to refresh the page, which has Ckeditor embedded, to make it show up</strong>. Otherwise, it is a default html text area. The oddest thing was that it worked fine unless I get in that page from my navigation bar.</p><p>Okay, that was really strange. I really thought it was the problem of Ckeditor. But it is not! I found out that was a problem of Tubolinks. Turbolinks is fast becasue it prevents the browser from reloading JavaScript and CSS everytime you hit a link.</p><p>What I could do was to shut down Tubolinks. But that’s not what I wanted to do. I still need Tubolinks to run on our apps. So, here’s what I did.</p><p>As its <a href="https://github.com/rails/turbolinks/#opting-out-of-turbolinks">readme</a> file says, I can <strong>opt out of Turbolinks</strong>. It is really easy.<br>Just put <strong>data-no-turbolink </strong>in the div I want it to work without Turbolinks.</p><h3>Problem Solved!</h3><blockquote>Updated 17/12/2015</blockquote><p>Thanks for <a href="https://medium.com/u/80798b2cad1f">Oliver Kriška</a> providing a better solution.</p><p>This solution do not need to disable Turbolinks.<br>Turbolinks loads JavaScript and CSS only one time. In ckeditor’s default JavaScript code, however, loads JavaScript every time the page calls it. That’s the main reason why I have to refresh the page to see the editor. Because I have to reload ckeditor’s JavaScript again.</p><p>What we can do is to write a initializer when visiting the page with ckeditor. Therefore, we don’t have to reload all the scripts and style again by refreshing. It only reloads ckeditor.</p><p>Here’s how:</p><ol><li>Give the text area an id</li></ol><pre>&lt;%= f.cktext_area :content, id: “ckeditor” %&gt;</pre><p>2. Add script to replace the original editor when the document is ready</p><pre>$(document).on(‘ready page:load’, function () {<br>  CKEDITOR.replace(‘ckeditor’);<br>});</pre><p>Note that in the “replace” method, you don’t have to put the id sign “#” before your id. It allows only the id’s name.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56b9204902d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication in Rails App]]></title>
            <link>https://tonyhsu23.medium.com/authentication-in-rails-app-e6a1e5c3829d?source=rss-49a941ea8aaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6a1e5c3829d</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Tony Hsu]]></dc:creator>
            <pubDate>Tue, 15 Dec 2015 10:14:40 GMT</pubDate>
            <atom:updated>2015-12-15T10:14:40.541Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, I’m going to talk about how to build authentication in rails app. I’ve used <a href="https://github.com/plataformatec/devise">Devise</a> before, but I really don’t understand how it works. Therefore I decided to build it from scratch. You might find that the following content looks like the course in <a href="https://www.codecademy.com/learn/rails-auth">Codecademy</a>. That’s because I leant from it. If you are interested in learning ruby on rails authentication, you might want to play that course. Also, this example is built on the rails app I’m building. You can find it on my page.</p><h4><strong>Gem and Model</strong></h4><p>Authentication is basically a log in, log out and sign up system, which users can see different contents based on which user is logged in. We’re going to use a gem called <a href="https://github.com/codahale/bcrypt-ruby"><strong><em>bcrypt</em></strong></a> to encode passwords so that people can’t see the them through database. Therefore the first step is to install bcrypt.</p><pre>gem ‘bcrypt’, ‘~&gt; 3.1.7’</pre><pre># note that the version must be higher than 3.1.7 to use      <a href="http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html">has_secure_password</a> in the model</pre><pre># then run &#39;bundle install&#39; in your terminal</pre><p>The concept is easy, we need a <strong>user model</strong> in order to store user name and password or even email. What is in the user model depends on what you need in your website. For me, I only want to get the user&#39;s first name, last name, email address and password. So, my migration looks like this</p><pre>def change<br>  create_table :users do |t|<br>    t.string :first_name<br>    t.string :last_name<br>    t.string :email<br>    t.string :password_digest<br>    t.timestamps null: false<br>  end<br>end</pre><p>Note that <strong><em>password_digest</em></strong> is a way to store your passwords without showing them to anyone. Then remember to run</p><pre>rake db:migrate</pre><p>After that, put the code below in the user model.</p><pre>has_secure_password</pre><h4>Views and Controllers and Routes</h4><p>First, we have to know what views and controllers are needed.</p><p><strong><em>Views:</em></strong></p><ul><li>a sign up page, in other words, <strong>creating a new user</strong>. So it’s a <strong>new.html.erb</strong> view for <strong>User.</strong></li><li>a log in page, so you’re <strong>creating a session</strong> to store information of a user. Then, it is a new.html.erb view without a model because we can get the inforamtion we want through User model.</li></ul><p><strong><em>Controller:</em></strong></p><ul><li><strong>UsersController</strong> for creating new user.</li><li><strong>SessionsController</strong> for creating a session.</li></ul><p><strong>Routes:</strong></p><ul><li>user resources</li><li>sign up path — <em>get</em> method.</li><li>log in path — entering log in data, so it’s a <em>get</em> method.</li><li>log in path — logging in, it’s a <em>post</em> method.</li><li>log out — delete session, it’s a <em>delete</em> method.</li></ul><pre>resources :users<br>get “signup” =&gt; “users#new”<br>get “login” =&gt; “sessions#new”<br>post “login” =&gt; “sessions#create”<br>delete “logout” =&gt; “sessions#destroy”</pre><h4>Sign Up</h4><p>In the <em>UsersController</em>, define a <em>new</em> action and a <em>create</em> action.<em> </em>In the new.html.erb view, make a form for the user to sign up. When the submit button is clicked, create action will be triggered.</p><pre>def create<br>  @user = User.new(user_params)</pre><pre>  if @user.save<br>    session[:user_id] = @user.id<br>    redirect_to root_path<br>  else<br>    redirect_to ‘/signup’<br>  end<br>end</pre><p>If the user data is successfully stored in database, assign the user id to session. This is important, since we need it for most of the web pages to check if the user is logged in or not. Also, remember to use <em>strong parameters</em> for mass assignment.</p><pre>private</pre><pre>def user_params<br>  params.require(:user).permit(:first_name, :last_name, :email, :password)<br>end</pre><h4>Log In</h4><p>The process of logging in is to fill user data first, check if the account exist. If it exist, check if its password is correct. Lastly, save the user id in the session.</p><p>This is how we do it.<br>In the <em>SessionsController</em>, we have two actions, <em>new</em> and <em>create</em>. You don’t need to put anything in the new action because we only need the user form in the view. After that, we identify the user in the database then redirect web page.</p><p><em>new.html.erb</em></p><pre>&lt;%= form_for(:session, url: login_path) do |f| %&gt;</pre><pre>  &lt;%= f.email_field :email, placeholder: “email” %&gt;</pre><pre>  &lt;%= f.password_field :password, placeholder: “password” %&gt;<br>  <br>  &lt;%= f.submit “Log In” %&gt;</pre><pre>&lt;% end %&gt;</pre><p><em>SessionsController</em></p><pre>def create<br>  @user = User.find_by_email(params[:session][:email])</pre><pre>  if @user &amp;&amp; @user.authenticate(params[:session][:password])<br>    session[:user_id] = @user.id<br>    redirect_to root_path<br>  else<br>    redirect_to ‘/login’<br>  end<br>end</pre><h4>Log Out</h4><p>The only thing we need to do to log out is to delete the user data saved in the session.</p><p><em>SessionsController</em></p><pre>def destroy<br>  session[:user_id] = nil<br>  redirect_to root_path<br>end</pre><h4>Define Helper Methods</h4><p>Most of the time, we have to check if the user is logged in or not. Some features in the app are not allowed for unknown users. For example, my blog application won’t allow unknown user to create a blog post or make an comment. In these cases, we can use helper methods defined in <strong>application controller</strong>. Since it is not possible to access model in views, we now can access through our helper methods.</p><ul><li>Case 1 — get the current user:<br>Sometimes, it is necessary to get current user’s information from session in the view.</li></ul><pre>def current_user<br>  @current_user ||= User.find(session[:user_id]) if session[:user_id]<br>end</pre><ul><li>Case 2 — require user:<br>Only logged in users are allowed to access specific contents. The <em>current_user </em>here is calling the method we defined above.</li></ul><pre>def require_user<br>  redirect_to login_path unless current_user<br>end</pre><p>After we define these methods, we need to let the controller know which are helper methods. So that we can use these methods in all the views. We must put these codes in the ApplicationController:</p><pre>helper_method :current_user</pre><p>There&#39;s no need to define <em>helper_method for </em>those we won&#39;t use in views. We can still get access of them in controllers.</p><p>For example, I want to use <em>require_user </em>in my <em>PostsController</em> to restrict access to creating and destroying blog posts. In order to follow the <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY principle</a>, we can define a <strong>before_action </strong>for new, create and destroy actions only. It will call <em>require_user </em>method before executing new, create and destroy actions.</p><pre>before_action :require_user, only: [:new, :create, :destroy]</pre><h4>Troubleshooting</h4><p>I encountered a problem when I&#39;m building this web app. Just so you know, I&#39;m using a MacBook Air. If you also have the same problem, this may help you. It&#39;s something about the path in Xcode (<a href="http://stackoverflow.com/questions/14334708/xcrun-cant-find-xcode-path">xcrun can’t find Xcode path</a>). I didn&#39;t have this problem when I was running on <strong>OS X v10.10 Yosemite</strong>. After I updated to <strong>OS X 10.11 El Capitan</strong>, something went wrong. I finally found the solution on stack overflow, here is the <a href="http://stackoverflow.com/questions/28706428/invalid-active-developer-path-on-mac-os-x-after-installing-ruby">solution</a>, I hope it helps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6a1e5c3829d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a blog using rails Part 3]]></title>
            <link>https://tonyhsu23.medium.com/build-a-blog-using-rails-part-3-8d2445c855d5?source=rss-49a941ea8aaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d2445c855d5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Tony Hsu]]></dc:creator>
            <pubDate>Thu, 19 Nov 2015 08:45:25 GMT</pubDate>
            <atom:updated>2015-11-19T08:46:25.417Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the third part of building a blog using rails. Please visit my <a href="https://medium.com/@tonyhsu23">page</a> to read the first two articles or click the links below if you haven&#39;t read them yet. Last time, I introduced three views. However, I am only going to demonstrate the <em>show.html.erb</em> page. If you are interested in the other two views (new, index), you can check in the <a href="https://github.com/tonyhsu23/blog">repository</a>.</p><h4>Build a blog using rails</h4><p><a href="https://medium.com/@tonyhsu23/building-a-blog-using-rails-part-1-configuration-1bb0f2815de0#.14yd1udyo">Part 1 Configuration<br></a><a href="https://medium.com/@tonyhsu23/build-a-blog-using-rails-part-2-features-439519d86a96#.w4vmszmhv">Part 2 Features</a></p><h3>Show Specific Post</h3><p>In the show page, we need do two things. Showing a post&#39;s content and comments which is related to it. We&#39;ll get the easiest one done.</p><h4>Post Content</h4><p>Remember we already found the post and saved it as a instance variable. This will make our task straightforward. We call the instance variable and show the content.</p><pre>&lt;%= @post.title%&gt; <br>&lt;%= @post.author %&gt;<br>&lt;%= @post.content %&gt;</pre><ul><li>The at sign is used to stand for instance variable. Putting two at signs will make it a class variable. Also, you can add any words or elements in this code block to make it like a real page. For example, make the title a header.</li></ul><pre>&lt;h1&gt;&lt;%= @post.title %&gt;&lt;/h1&gt;</pre><h4>Show Comments</h4><p>Looping through @comments and print all the comments.</p><pre>&lt;% @comments.each do |comment| %&gt;<br>  &lt;%= comment.respondent %&gt;<br>  &lt;%= comment.response %&gt;<br>&lt;% end %&gt;</pre><p>However I will separate the code into two parts and put some of them into a <em>partial. </em>The reason for putting it into a partial is because I want to render some part of the code when calling javascript. In the next paragraph I will explain. As a result, the code will be like...</p><pre><strong><em>show.html.er</em></strong></pre><pre>&lt;% @comments.each do |comment| %&gt;<br>  &lt;%= render comment %&gt;<br>&lt;% end %&gt;<br></pre><pre><strong>_comment.html.erb</strong></pre><pre>&lt;%= comment.respondent %&gt;<br>&lt;%= comment.response %&gt;</pre><h4>Comment Form</h4><p>Rails has a form helper when we have already defined resources in routes. It is the form_for helper. Since it is a nested route when we are calling <em>CommentsController</em>, we need to pass two variable to the helper. The form helper is smart enough to figure out the path. In this case, it will be calling <strong><em>/posts/:post_id/comments</em></strong> and link to the <strong><em>Create</em></strong> action in controller. Also, we&#39;ll be using Ajax to update the page without refreshing. So we need to set remote to <strong>TRUE</strong>.</p><pre>&lt;%= form_for([@post, @comment], remote: true) do |f| %&gt;<br>  &lt;%= f.text_field :respondent %&gt;<br>  &lt;%= f.text_area :response %&gt;<br>  &lt;%= f.submit &quot;submit&quot; %&gt;<br>&lt;% end %&gt;</pre><p>After submitting the form, we&#39;ll let Javascript handle the page. We do not need to define which format to use ( e.g. format.js ) because we need javascript only. It will render javascript for us. Therefore, create a <strong><em>create.js.erb</em></strong> file under the <strong><em>/views/comments</em></strong> folder(see below). Then prepend the new post.</p><pre>$(‘div.comments’).prepend(“&lt;%= escape_javascript(render @comment) %&gt;”);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*YvRnT93MtB18AYeO9OVBAw.png" /><figcaption>file directory(partial and js files)</figcaption></figure><ul><li>render @comment will find the <em>partial</em> named comment with an underscore ahead. <strong><em>_comment.html.erb</em></strong> is the partial file name.</li><li>Then what we did with javascript will affect this partial.</li><li>If you don&#39;t know what <em>escape_javascript</em> do, <a href="http://stackoverflow.com/questions/1620113/why-escape-javascript-before-rendering-a-partial">here</a> is the answer I found.</li></ul><p>If you cannot find any code snippets you want, please go check the source code below. Also, if there are any mistakes I made or misinterpreted something, <strong>please let me know</strong>.</p><p><a href="https://github.com/tonyhsu23/blog">tonyhsu23/blog</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d2445c855d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a blog using rails (Part 2 - Features)]]></title>
            <link>https://tonyhsu23.medium.com/build-a-blog-using-rails-part-2-features-439519d86a96?source=rss-49a941ea8aaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/439519d86a96</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Tony Hsu]]></dc:creator>
            <pubDate>Wed, 11 Nov 2015 09:50:07 GMT</pubDate>
            <atom:updated>2015-11-19T08:47:19.641Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@tonyhsu23/building-a-blog-using-rails-part-1-configuration-1bb0f2815de0">last article</a>, I have set the environment and configuration ready for my further development. Now, I am going to start writing features in this simple blog web application. This article will be focusing on how I build this web app and some difficulties I encountered instead of details of how to write rails application step by step.</p><h3>Relations &amp; Models</h3><p>Since I&#39;m building a simple blog, there are only two models I need, post and comment. The relation between post and comment is a one to many relation. To be more specific and clear, a post <strong><em>has many</em></strong> comments and a comment <strong><em>belongs to</em></strong> a post.</p><p>In the Post model, there are three columns.<strong> title</strong> (String), title of blog post<strong> content</strong> (Text), content of blog post<strong> author</strong> (String), author&#39;s name</p><p>In the Comment model, there are also three columns.<strong> response </strong>(Text), content of comment<strong><br>respondent </strong>(String), name of the person who comments<strong><br>post_id </strong>(Integer), the post&#39;s id which the respondent comments</p><h3>Routes</h3><p>I defined a root route and two resources in the routes.rb file.</p><ol><li>root route to show all blog posts</li><li>post resources</li><li>comment resources</li></ol><p>Because every comments must be in one of the posts, it makes sense to put comment resources in post resources, which makes nested resources. It looks like this:</p><pre>resources :posts do<br>  resources :comments<br>end</pre><p>In this way, for example, a index page of all comments is<br><strong>/posts/:id/comments</strong><br>instead of<br><strong>/comments</strong></p><h3>Views</h3><p>For now, I only need three views, index, new and show.<br><em>1. index.html.erb</em> is the root route, which shows all the posts.<br><em>2. new.html.erb</em> is the view which I can create a new post.<br><em>3. show.html.erb</em> shows the post&#39;s content including a title, contents and the author&#39;s name. Comments can also be created in this page.</p><p>At this point, I am not going to add CSS to these views. I want to establish these features first. They only include html, therefore, are not too great to look at. But I will fix it later in the future.</p><p>The details of views will be in the <a href="https://medium.com/@tonyhsu23/build-a-blog-using-rails-part-3-8d2445c855d5#.ktf1ac2bl">next article</a> because this is the part taking most of my time when I was coding. I encountered some problems and tried to fix them. These will all be included in the next one.</p><h3>Controllers</h3><h4>PostsController</h4><ul><li>For <strong>index</strong>, we just simply query all the posts by calling</li></ul><pre>@posts = Post.all</pre><p>then use it in the index view.</p><ul><li>In the <strong>show </strong>action, what we need to do is find the specific post and the comments in it. Also, an empty comment is created for the form which user can submit comments.</li><li>For <strong>new</strong> and <strong>create</strong> actions, create a post and save the data are their main purposes. Firstly, create an empty post for the <strong>form</strong> in <em>index.html.erb</em> to use.</li></ul><pre>@post = Post.new</pre><p>After the user finishing filling the form and clicking the submit button, the create action is then triggered. Save the data by calling</p><pre>@post = Post.new(post_params)</pre><p>As you can see, the parameter <strong><em>post_params </em></strong>is a <a href="http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters">strong parameter</a>, which is used in <em>mass assignment</em> situations. For example, when create or update data, there will be more than one column. That&#39;s when you should use strong parameter to prevent people from modifying your database, like authentication. You must permit which values are editable. So, how to create a strong parameter? Let&#39;s see.</p><p>Because we do not want to let other classes to get access to the parameter, as a result, we must make it private. Then just write down which parameter you requires<strong> </strong>and which values<strong> </strong>you want to get access to. In this case, I am going to create a new post, so I need the <strong>post </strong>parameter and its values, which is title, content and author&#39;s name.</p><pre>private</pre><pre>def post_params<br>  params.require(:post).permit(:title, :content, :author)<br>end</pre><ul><li>As for <strong>destroy</strong> action, everyone can delete any posts because there is no authentication in this app. I&#39;m going to ignore this since I&#39;m building a simple blog. So just see it as a practice of creating a destroy action. Basically, all we need to do is find the post and call the destroy method.</li></ul><pre>@post = Post.find(params[:id])<br>@post.destroy</pre><h4>CommentsController</h4><ul><li>The <strong>create</strong> action in CommentsController and PostsCotroller does&#39;t have much difference.</li><li>The <strong>destroy</strong> action is almost the same as the one in PostsController. The only different is that we needed to find the corresponding comments by the specific post.</li></ul><p>If you cannot find any code snippets you want, please go check the source code below. Also, if there are any mistakes I made or misinterpreted something, <strong>please let me know</strong>.</p><p><a href="https://github.com/tonyhsu23/blog">tonyhsu23/blog</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=439519d86a96" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>