Making Devise Mailers asynchronous

Devise is an awesome gem, it makes authentication for Rails apps really simple. One problem I faced was trying to make Devise mailers asynchronous. This kinda sorta worked, sometimes emails from devise will come almost immediately, sometimes it won’t come at all. Obviously, inconsistency is Not Good.

I figured the devise-async gem was to blame for this. So I decided to dive into it and see what I could find. Code reading is supposed to make you smarter anyway.

First thing I did was fork the gem, that way a copy appears on my github for me to modify and use. To use my own version of the gem I write this in my gemfile:

gem 'devise-async', git: "git://github.com/hewrin/devise-async.git"

With “hewrin” being my username.

Looking at tests are a good way to find out what a gem/app does. Unfortunately nobody told me about this when I first began diving in. All I did was insert “byebug” everywhere and send a devise email. But first, lets look at the Big Picture.

devise-async is a small gem, all the important stuff happens in the lib folder. To be more specific, the important stuff happens in the devise folder in the lib folder. Lets first look at the async.rb file.

From what I understand, this file is extending the Devise module by adding the Async feature. The file is pretty well commented, so its pretty simple to figure out what it does. The only interesting thing I found was mattr_accessor

mattr_accessor is like attr_accessor, difference is it creates getter/setter methods for modules instead of instances. This makes it easy for people to modify things in the initializers folder in a Rails app. The setup method at the bottom is what allows users to modify the configuration of the gem.

    def self.setup
      yield self

I haven’t encountered this before, it seems doing yield self loads up the whole Module, allowing us access to all mattr_accessor .

The kind people who created the gem even gave us an example:

    Devise::Async.setup do |config|
      config.backend = :sidekiq
      config.queue   = :default

In the example above, config.backend pretty much means Devise::Async.backend. So putting the above in a file in my initializers folder will set Sidekiq as my backend and the queue name as default.

Finally, at the bottom there is a method that adds the Async module to devise, this is what allows us to add devise :async in our model files to make the mailers asynchronous, just like when we add :confirmable to send confirmation emails.

The Devise.add_module method is quite interesting. Below is the source code of the method, taken from Devise:

    def self.add_module(m)
      class_eval <<-METHOD, __FILE__, __LINE__ + 1
        def #{m}?

This…will be discussed in my next post.


Seeding Stuff

Creating a new app is really fun. Whats not so fun is having to populate the database with dummy data so you can test how things work. Even more not fun is when changes happen (yes its true, requirements sometimes change, I’ve actually seen it with my own eyes) and you have to drop the database and repopulate it again.

Thankfully, Rails has the db:seed rake task. All you have to do is modify the seed.rb file in the db folder.

There are plenty of ways to do this:
(1) Using code

      { :meal => 'Lunch', :price => 450.00},
      { :meal => 'Dinner', :price => 450.00}
     ].each do |c|
      Price.create!(:meal => c[:meal], :price => c[:price])

This takes a hash and creates two Price objects. I think arrays would work just as well.

(2) Using CSV

require 'csv'
CSV.foreach("config/languages.csv", { encoding: "UTF-8", headers: true,header_converters: :symbol, converters: :all}) do |row|

This takes a CSV file, in this case stored in the config folder.

headers: true makes the first row of the CSV file (in this case “name”) as the header. What this means can be shown below:

 CSV.foreach("config/languages.csv", { headers: true }) do |row| print row.to_hash end

Wil produce

  {"name"=>"English"}{"name"=>"Danish"}{"name"=>"Mandarin Chinese"}

header_converters: :symbol as its name suggests, makes the header into a symbol, I guess the default is a string

(3) Using text files

open("config/nationalities.txt") do |states|
  states.read.each_line do |national|
  name = national.chomp
  Nationality.create!(:name => name)

Here we use a text file, with all the nationalities having their very own line.
So you might wonder, why is there a double block in here? The answer is when we open config/nationalities.txt it returns a File object.(In this case, called “states”)
So we have to create another block that reads each line of the file individually. Then we can safely create Nationality objects with each line.

There should be more ways to do it. These are just the ones I’ve found.


Little Steps

Hmm, Ruby and Ruby on Rails breaks into so many branches, I can learn testing, I can learn threading, I can learn metaprogramming. So many books to read too. There is Practicing Rails, Rebuilding Rails and even Practical Object Oriented Design in Ruby. And I haven’t even fnished the Pickaxe book yet!

But, Javascript is really important! I need to learn the MEAN stack and fast! I also heard that ES6 is coming up soon, I gotta learn that as well. My CSS sucks, I have no front end skill. I can barely make a website desktop responsive, never mind mobile responsive. My frontend skills need levelling up, NOW.

I read an article that “Real Men Code in C”. C is the mother tounge of programming. I can’t call myself a programmer if I don’t know C. And whats this functional programming thing I keep hearing about? Haskell makes you smarter? Erlang is good for concurrency? 

Thats an accurate transcript of what goes on in my head when I’m trying to decide what to learn next. A few months ago I started allocating “learning time” a few hours a week to learn something new. This noble activity usually ends up with me web surfing something totally unrelated. Usually some obscure thing I found on Hacker News.

I admit its partly because I have focusing issues that date back to childhood. But its also because I have a fear of “missing out”. When I first started this web developer gig, I kept reading how “5 years from now, everything you know will be obsolete” or “You must be continuosly learning”. I guess that spooked me into thinking I wasn’t learning things fast enough and that I should be mastering more complex (i.e incomprehensible) subjects. I have this weird habit where if the subject is so hard that I’m lost after the first paragraph, then I think it MUST be useful

After realizing that I’ve clocked about 50 “learning time” hours and haven’t actually learned anything, I’ve started to reassess my choice of topics. Instead of looking a one big topic like CONCURRENCY, I now try to master little topics. like maybe how partials work in Rails. I also liked the technique taught in Practicing Rails. The Tiny Apps method, where you create a tiny app to try new gems or a new feature first. Its awesome when you can test something out almost immediately. Especially for someone like me who can get distracted by literally anything.

I guess the point is to break everything into the smallest piece possible. Don’t make grand plans to study everything about Javascript for two hours, focus on sitting down to learn one specific thing for 10 minutes. I usually find myself pushing forward after those ten minutes to learn something else although there were plenty of times where I immediately stopped to do something else. Thats fine though, getting 10 minutes of learning time a day is 10 minutes more than I got previously.

 Don’t worry about getting good now, take your time. Small steady progress is better than giant steps that end up not happening . As a wise man once said, “How do you eat an elephant? One bite at a time”


10 more things I learned working at a Dev Shop

Continuing from my previous post, I’ll be listing 10 more thing I learned from working at Web Development Company. Whats that? I only could do 3 last time but I’m shooting for 10 now? Like most things I do, there is a method to the madness. I read “Choose Yourself” by James Altucher the other day. One of his many many tips is to exercise your brain. You do this by listing 10 ideas on anything everyday. He notes that anyone can do 4 or 5, but 10 “makes the brain sweat”

I’ve been doing this practice for the past week, and boy has it tired out my brain. Doing it on an empty stomach does not help. One thing to note before I start, he warned in the book that your ideas will be horrible at first, they only get really good in 6 months or so. So if you find my list stupid, thats why.

So lets get sweaty!

1) Things always go wrong. I touched on this in my last post. Every time I pushed code into production, I’ll spend many many minutes (hours) frantically repairing stuff. Sometimes while the client was checking the website out. I wasn’t smart enough to write tests from the beginning. Learning to write tests is definitely on my to-do list.

2) Funny I mentioned to-do lists, cause my next point is about them. I don’t think I get the same benefit from to-do lists as other people seem to do. I’ll write things down on a piece of paper and promptly forget about it. Or I’ll write too many things, can’t decide which one to do and do nothing. I’ve started replacing my to-do list with a To-Do Thing. Where I usually just choose ONE important thing to do. Once I finish that. I create a new To-Do Thing. This has a bad side though. Sometimes after completing my Big Thing, I coast for the rest of the day. Usually when its almost 5 and I’m out of juice. So like all time managing/productivity techniques, the best time to do this is “it depends”

3) Documentation in software could really use some upgrading. I’m not sure if its because I lack intelligence or they did a half assed job. I bet its the former. Whatever, it would be nice if popular API’s had good,easy to follow examples. That there is a niche an aspiring blogger can fill…..

4) Making things simple is way harder then it sounds. I can’t remember the number of times I’d try explain something to my coding partner and he’ll just say “whaaaat?” Its true explaining things in a coherent manner isn’t one of my strong suits. One thing I’ve tried to do is to start from the very beginning. After that, while speaking slowly, build on that and explain the next point. Metaphors should only be used when you have the listeners full attention. That is pretty rare in this day and age.

5) Requirements gathering is really important. I know this sounds obvious, but its worth repeating, Really Important. In the Pragmatic Programmers, they talk about contracts and how they “protect” both sides. All I can add to that is yes. Make sure all requirements are gathered and agreed upon. Its also a really good idea to show stuff frequently to the client. At least keep them in the loop. That way they feel less anxiety (hopefully) and they can point out mistakes or modifications early

6) Keeping with the topic of clients, I got to learn to talk to them better. I need to learn laymans language. Whenever I said something I could tell it was too technical for them, but I couldn’t help myself. This ties up with point 4, it’s probably a level above. If you can explain things simply to a client in a way they can understand, then you should have no problems speaking to a co-worker.

7) Front-end is hard. I’ve always loved doing back-end development. Working on cool data structures and algorithms. I thought it was challenging enough. Little did I know the horrors of front-end, when the client gives you feedback saying “button not green enough”. I’m sitting there thinking “There’s more than one green?”. I admit I lack aesthetic sense. I can barely differentiate between a color and light of a specific wavelength entering my eye. I have to say though. I’m fascinated by how certain designs can make people “feel things”. If its true, its borderline mind control. Like I watched a designer working on a logo. And the client was like ” I want this logo to make people feel this and that and this…..”. I was gobsmacked. I mean, I’ve heard about “A picture tells a thousand words”, I didn’t think it was literally true!

8) Do learning on your own time. I noticed I didn’t have much time to learn much while working, usually cause we were chasing a deadline or two. Although I’ve done plenty of things on the job, I  didn’t spend lots of time really getting to know it deeply. There was always something new to create or fix. I’ve heard about how learning doesn’t happen much when you’re panicked and under pressure. And I’ve noticed the things I did didn’t “stick in the brain” much. I usually have to review what I did at night. Which come to think about it, that was what I did at the Bootcamp

9) Speaking of Bootcamps, mentors are priceless. To actually be able to learn from someone senior is a luxury unavailable in my workplace now. (Not the companies fault, its still new) So every so often we go back to the scene of our Bootcamp to hang out with the mentors and ask them questions. I noticed though, most of my problems, the ones that I really get stuck on. Are usually due to carelessness. A hidden typo, An uncapitalized letter, little things like that. Perhaps its less to do with mentors and more to do with my own carelessness. Having said that, its still pretty cool having someone you can go to for advice.

10) Which brings me to my last point. This has been bugging me for a while. We don’t really have much in the way of Best Practices in our team. We barely have Practices. Its more of a “Make Things Up As We Go Along” thing. I know Best Practices can be overused and are not applicable to every case. Still, it would be nice to have some guidance on what we do. If only to make the whole app consistent. One of these days my big To-Do Thing will be to create a list of Best Practices Guidelines. (Or even Better Practices Guidelines) Instead of the big ball of mud generator I have now.

Whew! 10 things! My brain is pretty sweaty right now. That was a good exercise though. It was pretty fun too. Until next time


Reflections after almost nearly 2 months

Hello there!

After I obviously ran out of whatever juice made me create this blog in the first place, I’m back for another crack at this. I haven’t been ignoring this blog just due to laziness, I’ve been really busy. Working two jobs while also trying to do a freelance project takes a surprising large amount of your time.

Having said that, I haven’t forgot this blog entirely, all this while the Idea Monkey in my head has been mostly chucking bananas and poop at my brain  diligently taking notes in my head. Every once in a while he’ll think of something worth jotting down. Sadly, I never had the time to jot anything down, so I’ll just make things up here, in no particular order

  1.  I noticed my “lack of time” usually came from wasting it. When I look back at the end of the day, cursing the world and life in general because I got so little done, it was usually cause I wasted it on Youtube or blogs. Usually both at the same time. Having League of Legends installed on your computer really doesn’t help either. I read a book called The Power of Habits which says that a habit is something we do without thinking after receiving a certain cue, the thing we do often comes with a “reward” which will then reinforce this habit . An example would be Get Hungry (cue) —–> Eat Cookie (habit we do) ——> Mmmm,Cookie good! (Reward). I think my cue starts when I want to begin work, my habit is doing anything but work, and my “reward” is shame and regret. I’m positive there is a way around this. (There is, its written in the Power of Habits book. Like most things worthwhile, its Simple but not Easy.)
  2. Number 2 is related to my programming misadventures, but it’ll probably apply to other things too. I noticed I was often so hesitant to start a new feature at work. I’m not sure if its a comfort zone thing or I’m just dull. When I want to begin anything I’ll stare at it for what feels like hours, reading the same documentation over and over again. I was positive I’ve overcome this bad habit in the Code Division bootcamp. I was taught to always try things and see how it goes. And every single time, I’ll try things and it magically turns out OK……eventually, after lots of debugging.
  3. I read a bit in the “Pragmatic Programmer” about defensive programming. I think I read this book to early. As I didnt understand more than half of what was written. I’ll probably need to read it again soon. One thing that stuck to me was the concept of defensive programming, where you don’t trust yourself to not make mistakes. And so you code defensively. Coding defensively would have really helped me when I pushed the app I built into production. It probably wouldn’t have solved all the bugs, but I’m sure it would have caught at least some of them. Another important thing would probably be creating a glossary. That would really be helpful when talking with clients. I guess sometimes I get to caught up coding the app that I forget that other people don’t know much about the greasy innards of my code. I guess its a Curse of Knowledge thing.


Well, this took longer than I thought. (see “Wasting Time” in point number 1) It’s getting really late on my side of the globe so I bid you all good night!



I read books too!

I’ve been way to busy this week to blog about my programming exploits, so I thought I’d talk a bit  about a book I read called Pragmatic Thinking and Learning.

I’ve read this book a few times already, partly because its quite interesting, and partly because it said “Reading is one of the worst ways to learn” So I figured reading it a few times might help me.
The first and probably most important tip this book gives is “Always consider the context” Things don’t occur in a vacuum, people don’t behave independently, there is always an additional why or external factors that affect everything. Take people, for example. Most people are pretty decent, but under stressful conditions almost anyone can turn into a cursing,sarcastic,snide jerk. Understanding that is the secret to not getting pissed off by everyone.
The book places a high value on intuition, it states that our brain consists of a L-mode and a R-mode (This doesn’t  refer to left and right)
L-mode is logical, linear,analytical etc
R-mode is intuitive, holistic, non-linear and even non-rational
Since this book is written from the viewpoint of a programmer, the writer is looking to get in touch  with his R-mode, He states that the L-mode is the “Little voice in your head” that chatters nonstop in your head. whereas the R-mode is non-verbal signs, like images. Only one of these modes can dominate the mind at once, so the author suggests letting the R-mode flow first (synthesize) , and then analyze your creation with L-mode.
He also defines the skills progression from Novice to Expert. A novice has no knowledge of context and has to follow rules, an Expert can see the Big Picture and also has an intuitive feel for things. I think this is why he emphasizes the R-mode so much, its a necessary part of  being an Expert.
R-mode can’t be forced, it can only be invited out, even then the flow of ideas/images/thoughts can’t really be controlled. You can’t predict when/where or how ideas will appear, so the author recommends writing down any ideas in a notebook. Another way to harvest R-mode ideas is to write things down.

Some of the advice/exercises are really interesting, in one exercise the book gives you a picture that is upside down. And without thinking of the picture, try to redraw it but just thinking of the picture as individual lines. For example, if it was a picture of an elephant, don’t think of it as an elephant, just think of it as a bunch of lines joined together. (That is why turning the picture upside down helps)

I tried this exercise, and after I got the hang of it, the result was for me above average (meaning that it was just very bad instead of absolutely terrible). I think what this exercise does is “quieten your L-mode voice”. If you knew it was an elephant, your L-voice would be all “Its an elephant! It looks like this!!!!”

Yup, finally cracked image uploading on wordpress, now I wished I didn't
Yup, finally cracked image uploading on WordPress, now, boy am I regretting that now

The above drawing technically sorta kinda looks like an elephant, but still….I’m ashamed of myself.

But when you ignore the fact that its an elephant and just focus on the lines, your L-mode voice quiets down and you can focus on just drawing the best damn elephant you can draw.

There are still plenty of great tips and tricks in this book, too many to list here, so i suggest you get the book, and read at least twice.


Sorting Algorithm

Today I learned a sorting algorithm, this program takes a list of words and sorts them according to how they would appear in a dictionary.
So first of all, there is an array unsorted, this contains all the unsorted words.
Next we take out one word (called smallest) from the array and use a do method to compare it with all the other words in the unsorted array. (in this case called tested_object)
If the tested_object is smaller than the smallest, then the smallest  is placed into another array.  still_unsorted array. and the tested_object  becomes the new smallest
If the tested_object  is larger than the smallest, than the tested_object is placed in the still_unsorted  array 
Because we iterate through the entire unsorted  array, the last smallest remaining will actually be the “smallest” (this means it will appear first in the dictionary)
We than use recursion by using the same method  as above only this time we use still_unsorted instead of sorted
Below is an example code (taken from Learning to Program Ed.2)
def recursion_array(unsorted sorted)
    smallest = sorted.pop
    still_unsorted = []
    unsorted.each do |tested_object|
    if tested_object < smallest
        still_unsorted push smallest
        smallest = tested_object
        still_unsorted.push tested_object
sorted.push smallest
recursion_array(still_unsorted sorted)
   This is an example of recursion, which is the act of cursing over and over, which means the program is calling a method repeatedly, but each method call brings the loop closer to the answer/intended output/solution.
I know this has been wildly exciting, stay tuned as I delve into even more exciting algorithms, and maybe one day even be able to publish code in a semi-decent way.