Author: tejas

  • Why Should Java Developers Give Grails a Chance?

    Java has an ecosystem that has matured through years of development, establishing it as one of the most reliable platforms out there. Yet it lacks the means necessary to get the job done quickly, especially for things like web applications. In an attempt to avoid frustrations with these types of issues, developers often opt instead for implementation languages and their modern web frameworks, such as Ruby with Ruby on Rails, Python with Django, and so on. Unlike Java, these provide a much more streamlined path to building a web application.
    Fortunately, for Java developers wanting to build web applications, there is a better way, and it involves Grails. In this article, we will see how Grails with Groovy is a viable alternative in the JVM realm. We will look at some examples where Grails is appealing to us as Java developers and might tempt someone else to give it a shot as well.

    The Story

    In a startup I worked for, we had this exact problem. We had a Spring application which was becoming a pain to work with. With it growing larger and larger, we soon found that refactoring and adding functionality was taking us way longer than it should. Combining that with some other motivations led us to decide to rewrite our core application. We were also open to changing or replacing existing technology stack. Grails looked like a viable choice since it runs in the JVM and is built on top of technologies we already knew. It uses the Groovy programming language but at the same time allows you to mix it with Java. So we took the plunge.

    Full Speed Ahead

    One thing Grails really excels at is making it easy to start a new project. It is as simple as running a command which creates the project structure with all the folders needed for the classes you will add later. Adding model classes, controllers, services and web pages takes a similarly minimal amount of effort. The only thing you need to take care of is naming and placing stuff correctly. Unlike Java, there is virtually no boilerplate code that needs to be there just because it needs to be. This is partially made possible by using Spring and Hibernate which are two of the pillars of Grails, as well as the concept of coding by convention. To run the project, Grails comes bundled with Apache Tomcat as a development server. All we have to do is run the project in our IDE and the server will be fired up with our code deployed. Also, the Grails’ Object Relational Mapping (GORM)with Hibernate will take care of creating the database for us. To use an existing database, we need to configure the JDBC connection properties or just leave it by default to use an in-memory instance. Once the server with Grails is running (takes a little bit more than a Spring MVC application), we can modify the code and the hot deploy functionality will keep our debug session equipped with the latest version. The only classes that cannot get reloaded this way are the entity classes.
    Populating the database can be done by using SQL scripts, but that can get tedious. All Grails projects contain a Bootstrap class which will be run when our application is run. In this class, we can store or modify data and thus initialize our application state. This proved very useful for us so we have some test cases in development version right away.

    Manipulating Data

    One of the things that immediately caught our attention with Grails was the ease of working with data. Reading from the database is a task that needs to be done over and over. And many times it is simple. Like fetching one or more entities which meet certain criteria and then aggregating them. Why not use a dynamic finder for that? It is a way of querying data where methods are dynamically created at runtime. All you have to do is follow a naming convention.

    def users = User.findAllByLastNameLikeOrAgeGreaterThan(‘Doe%’, 30)
    

    The line above line will fetch all User objects with last name starting with “Doe” or age greater than 30. Yes, not a very sophisticated case but you get the gist.
    What if we wanted to filter this list additionally for the ones that have the “failedLogins” property greater than 10? And what if we wanted to sort them by their date created? And what if we wanted to get their first names concatenated or find the maximum age of the users returned?

    users = users.findAll() { it.failedLogins > 10 }
    users = users.sort { it.dateCreated }
    def firstNamesString = users.firstName.join(‘, ‘)
    def maximumAge = users.age.max()
    

    The above examples may look simple, but they show how powerful Grails can be for querying, filtering, and manipulating data. In Java 8, you can achieve similar results for some of these cases, but it will still require more code than Grails.

    Sometimes I Want to Create Differently

    A dynamic constructor or named argument constructor is a feature that many of us wanted to have in Java. It’s nice to define which constructors a certain class allows, but in many cases you just want to set some properties and get the darn instance. Groovy adds a special constructor for each entity which basically takes the elegance of a map as input and sets the properties with the map entries.

    def Person = new Person(name: 'Batman', age: 57)
    

    This approach leads to code that is much more expressive and avoids the need for all the constructor boilerplate code.
    And BTW, here are some examples of the awesomeness and elegance of Groovy’s maps:

    def emptyMap = [:]
    def map = [bread:3, milk:5, butter:2]
    map[‘bread’] = 4
    map.milk = 6
    

    This is another example of how the code can be short and simple, yet powerful. It shows how inline initialization can be used and how map values can be manipulated in a way similar to object properties. No need to call traditional Java methods for basic manipulation, unless you really want to.

    We Need More Power!

    Of course, there is no framework that can do everything, but when we’re filling in the gaps, we should see what else might already be available before trying to implement our own solution. To expand our arsenal of Grails-based functionality, we can use Grails Plugins. Installing a plugin is simply done by adding another line in the BuildConfig class that is present in every Grails project (code convention strikes again!).

    compile ':spring-security-core:2.0-RC4'
    

    The line above adds the Spring security core to our application and there is virtually no more configuration needed to incorporate this functionality.

    It’s similar to using Maven dependencies (which you can also reference in the same config class), but the plugins are usually larger blocks that contain the whole functionality.

    That being said, let me tell you about a case we had to deal with. We needed to implement a search spanning across several data entities. Grails has an Elasticsearch plugin which is a breeze to use. As mentioned before, we only need to reference the plugin in the config file and we’re good to go. If we want to search for entities of a certain class, we just need to add a static “searchable” property to that class. And if we want, we can even limit the properties that will be allowed to be searched.

    class User {
        static searchable = { only = name }
        String name
        Double salary
    }
    

    It is so little code, but under the hood, Grails and the Elasticsearch plugin will automatically index all users by name and enable us to search by name. The actual search call is also very concise:

    User.search("${params.query}")
    

    If we don’t want to, we will never have to touch the Lucene index. All will be done auto-magically for us. The plugin even has an API for displaying search results – it can highlight the match found inside searched text. This is just an example how a plugin can provide a huge bundle of functionality which can make us that much more efficient by avoiding the need for us to implement it ourselves.

    We Still Need More Power

    Plugins are great, but sometimes we don’t need a whole plugin, we just want something extra. Do you remember the last time you wanted to have an additional method on an existing Java class but you didn’t want tp (or couldn’t) extend/override them? In Groovy, you can add methods and properties to existing classes, or even just certain instances of them. For instance, you can add a formatting method to the java.util.Date class which is awesome when you want to format dates consistently and just don’t want to write static util classes or define various filters.

    Date.metaClass.formatDate = { delegate.format("dd.MM.yyyy") }
    

    What if you want to sort a list of users by a computed value and you only need this in one case (i.e. adding a new method in User class would be polluting)? You could add a property on each of those instances and then just sort or filter the collection by that property:

    user.metaClass.computedProp = 312 * 32 * 3
    

    Groovy authors have already added a lot of enhancements to some of the core Java classes, so we don’t have to. Below are some examples.
    Using “minus” to remove all elements from a collection that are present in another collection.

    assert [1, 2, 3, 4, 4, 5] - [2, 4] == [1, 3, 5]
    

    Additional methods for manipulating java.util.Date objects which come in handy so many times, such as adding/subtracting days from dates or getting/setting a certain field of the date without converting it to Calendaror using additional libraries.

    def yesterdayAllMyTroublesSeemedSoFarAway = new Date() - 1
    def myAwesomeAnniversaryYear = myAwesomeDate[Calendar.YEAR] + 1
    myAwesomeDate.set(year: myAwesomeAnniversaryYear, second: 0)
    

    When you want to really get descriptive with date manipulation, you can simply use the Groovy added TimeCategory class:

    use (TimeCategory) {
    println 1.minute.from.now
    	println 10.hours.ago
    	def someDate = new Date()
    	println someDate - 3.months
    }
    

    A Hammer and a Nail

    Then there are the IDEs. Eclipse-based GGTS and IntelliJ IDEA are set-up for working with Grails. They understand the project structure (and will help you navigate through folders and resources) and have shortcuts for the commands you will most often use (e.g., add controller, add a page, run a project, etc.). With Grails you will execute commands (to run a project or set-up a new plugin functionality) and you will need different configurations, which is also covered by the IDEs. Code completion works nicely in Grails web template pages where you will often reference controllers and actions.There are also other IDEs that can be used with Grails such as Netbeans, TextMate, Emacs and others.

    What About the Dark Side?

    Just as with everything in life, there are caveats with Grails also. There is a lot of magic being done under the hood which can often be a good thing, but sometimes the result will not be what you expected. Bugs will happen just because of not using typing (yes, types are optional in Groovy) and not being careful enough. And maybe you won’t notice an error until it’s too late. Also, it’s very tempting to write one-liners to impress your coworkers. And yourself. But these powerful lines of code might not be as self-explanatory to your coworkers. Or even to yourself in a couple of months. That’s why I think Grails demands more programming discipline than some of the more traditional frameworks.

    Time is Money

    Coding shouldn’t take more time just because your current framework demands it to. Especially with the increasingly huge number of startups these days, it’s important to focus on the tasks that really matter and to be as efficient as possible. Time is indeed money and time to market is critical. You need to be able to act quickly and implement the solution before time runs out and your competition beats you to it.
    My friends working with Ruby on Rails or Python/Django have long been telling me how cool those technologies are. And it really felt silly to think how much more time it took me in Java to write code that stores something in database and displays it in a web page. Grails may indeed be a useful answer. It’s not that you couldn’t do this with pure Java, Spring MVC, and Hibernate. You could. Your application might even run a little faster. But you will get the job done faster with Grails.
    This post originally appeared in Toptal Engineering blog

  • Responsive / screen size wise font-size using CSS

    Since there are lots of improvements is happening in CSS3 and still most of developer and designer are unaware of it.
    So, Now let me present the new tag they introduce in CSS3 for Responsive font-size is : vw, vh, vmin, vmax
    With this font size type, it will increase and decrease font size according to screen or browser size. This is very helpful as generally we use px but with px there is an issue when user opens it on large screen then they are not able to see proper font size so to fix this issue we increase that font in px and then the main issue occur for small screen devices because they see very big font on their tiny screen. to prevent this issue we add media query but my question is that how many media query you will write. so to save this extra effort we can use new font size type.
    With the help of vw, vh, vmin, vmax we define font size and with this, we don’t have to write media queries for each screen.
    Example:
    vw:
    Divs with color shade:

    <div class="grid">
      <div class="grid__item"></div>
      <div class="grid__item"></div>
      <div class="grid__item"></div>
      <div class="grid__item"></div>
      <div class="grid__item"></div>
      <div class="grid__item"></div>
      <div class="grid__item"></div>
      <div class="grid__item"></div>
    </div>
    .grid::before,
    .grid::after {
      clear: both;
      content: '';
      display: block;
    }
    .grid__item {
      box-sizing: border-box;
      float: left;
      height: 50vw;
      padding: 2em;
      width: 50vw;
    }
    .grid__item:nth-child(1) {
      background-color: #ff4433;
    }
    .grid__item:nth-child(2) {
      background-color: #ff5533;
    }
    .grid__item:nth-child(3) {
      background-color: #ff6633;
    }
    .grid__item:nth-child(4) {
      background-color: #ff7733;
    }
    .grid__item:nth-child(5) {
      background-color: #ff8833;
    }
    .grid__item:nth-child(6) {
      background-color: #ff9933;
    }
    .grid__item:nth-child(7) {
      background-color: #ffaa33;
    }
    .grid__item:nth-child(8) {
      background-color: #ffbb33;
    }
    

    Output: https://codepen.io/timseverien/pen/uhzgo
     
    Screen wise font size:

    <div class="container">
      <h1>My special headline</h1>
      <p>Re-size the viewport and see the headline magically resize!</p>
    </div>
    .container { text-align: center; }
    h1 { font-size: 5vw; }
    

    Output: https://codepen.io/timseverien/pen/rkhgo
    In this, you can also use vmax instead of vw.
    This is very helpful but the major drawback is that it is supported by only modern web browsers.

  • Hunting Down Memory Issues In Ruby: A Definitive Guide

    I’m sure there are some lucky Ruby developers out there who will never run into issues with memory, but for the rest of us, it’s incredibly challenging to hunt down where memory usage is getting out of hand and fix it. Fortunately, if you’re using a modern Ruby (2.1+), there are some great tools and techniques available for dealing with common issues. It could also be said that memory optimization can be fun and rewarding although I may be alone in that sentiment.
    Hunting Down Memory Issues In Ruby
    As with all forms of optimization, odds are that it will add code complexity, so it’s not worth doing unless there are measurable and significant gains.
    Everything described here is done using the canonical MRI Ruby, version 2.2.4, although other 2.1+ versions should behave similarly.

    It’s Not a Memory Leak!

    When a memory issue is discovered, it’s easy to jump to the conclusion that there’s a memory leak. For example, in a web application, you may see that after you spin up your server, repeated calls to the same endpoint keep driving memory usage up higher with each request. There are certainly cases where legitimate memory leaks happen, but I’d wager they are vastly outnumbered by memory issues with this same appearance that aren’t actually leaks.
    As a (contrived) example, let’s look at a bit of Ruby code that repeatedly builds a big array of hashes and discards it. First, here’s some code that’ll be shared throughout the examples in this post:

    # common.rb
    require "active_record"
    require "active_support/all"
    require "get_process_mem"
    require "sqlite3"
    ActiveRecord::Base.establish_connection(
      adapter: "sqlite3",
      database: "people.sqlite3"
    )
    class Person < ActiveRecord::Base; end
    def print_usage(description)
      mb = GetProcessMem.new.mb
      puts "#{ description } - MEMORY USAGE(MB): #{ mb.round }"
    end
    def print_usage_before_and_after
      print_usage("Before")
      yield
      print_usage("After")
    end
    def random_name
      (0...20).map { (97 + rand(26)).chr }.join
    end
    

    And the array builder:

    # build_arrays.rb
    require_relative "./common"
    ARRAY_SIZE = 1_000_000
    times = ARGV.first.to_i
    print_usage(0)
    (1..times).each do |n|
      foo = []
      ARRAY_SIZE.times { foo << {some: "stuff"} }
      print_usage(n)
    end
    

    The get_process_mem gem is just a convenient way to get the memory being used by the current Ruby process. What we see is the same behavior that was described above, a continual increase in memory usage.

    $ ruby build_arrays.rb 10
    0 - MEMORY USAGE(MB): 17
    1 - MEMORY USAGE(MB): 330
    2 - MEMORY USAGE(MB): 481
    3 - MEMORY USAGE(MB): 492
    4 - MEMORY USAGE(MB): 559
    5 - MEMORY USAGE(MB): 584
    6 - MEMORY USAGE(MB): 588
    7 - MEMORY USAGE(MB): 591
    8 - MEMORY USAGE(MB): 603
    9 - MEMORY USAGE(MB): 613
    10 - MEMORY USAGE(MB): 621
    

    However, if we run more iterations, we’ll eventually plateau.

    $ ruby build_arrays.rb 40
    0 - MEMORY USAGE(MB): 9
    1 - MEMORY USAGE(MB): 323
    ...
    32 - MEMORY USAGE(MB): 700
    33 - MEMORY USAGE(MB): 699
    34 - MEMORY USAGE(MB): 698
    35 - MEMORY USAGE(MB): 698
    36 - MEMORY USAGE(MB): 696
    37 - MEMORY USAGE(MB): 696
    38 - MEMORY USAGE(MB): 696
    39 - MEMORY USAGE(MB): 701
    40 - MEMORY USAGE(MB): 697
    

    Hitting this plateau is the hallmark of not being an actual memory leak, or that the memory leak is so small that it’s not visible compared to the rest of the memory usage. What may not be intuitive is why memory usage continues to grow after the first iteration. After all, it built a big array, but then promptly discarded it and started building a new one of the same size. Can’t it just use the space freed up by the previous array? The answer, which explains our problem, is no. Aside from tuning the garbage collector, you don’t have control over when it runs, and what we’re seeing in the build_arrays.rb example is new memory allocations being made prior to garbage collection of our old, discarded objects.

    Do not panic if you see a sudden rise in the memory usage of your app. Apps can run out of memory for all sorts of reasons – not just memory leaks.

    I should point out that this isn’t some sort of horrible memory management issue specific to Ruby, but is generally applicable to garbage-collected languages. Just to reassure myself of this, I reproduced essentially the same example with Go and saw similar results. However, there are Ruby libraries that make it easy to create this sort of memory issue.

    Divide and Conquer

    So if we need to work with large chunks of data, are we doomed to just throw lots of RAM at our problem? Thankfully, that’s not the case. If we take the build_arrays.rb example and decrease the array size, we’ll see a decrease in the point where memory usage plateaus that’s roughly proportional to the array size.

    This means that if we can break our work into smaller pieces to process and avoid having too many objects existing at one time, we can dramatically reduce the memory footprint. Unfortunately, that often means taking nice, clean code and turning it into more code that does the same thing, just in a more memory-efficient way.

    Isolating Memory Usage Hotspots

    In a real codebase, the source of a memory issue will likely not be as obvious as in the build_arrays.rbexample. Isolating a memory issue before trying to actually dig in and fix it is essential because it’s easy to make incorrect assumptions about what’s causing the problem.

    I generally use two approaches, often in combination, to track down memory issues: leaving the code intact and wrapping a profiler around it, and monitoring memory usage of the process while disabling/enabling different parts of the code I suspect could be problematic. I’ll be using memory_profiler here for profiling, but ruby-prof is another popular option, and derailed_benchmarks has some great Rails-specific capabilities.
    Here’s some code that’ll use a bunch of memory, where it may not be immediately clear which step is pushing up memory usage the most:

    # people.rb
    require_relative "./common"
    def run(number)
      Person.delete_all
      names = number.times.map { random_name }
      names.each do |name|
        Person.create(name: name)
      end
      records = Person.all.to_a
      File.open("people.txt", "w") { |out| out << records.to_json }
    end
    

    Using get_process_mem, we can quickly verify that it does use a lot of memory when there are a lot of Person records being created.

    # before_and_after.rb
    require_relative "./people"
    print_usage_before_and_after do
      run(ARGV.shift.to_i)
    end
    

    Result:

    $ ruby before_and_after.rb 10000
    Before - MEMORY USAGE(MB): 37
    After - MEMORY USAGE(MB): 96
    

    Looking through the code, there are multiple steps that seem like good candidates for using a lot of memory: building a big array of strings, calling #to_a on an Active Record relation to make a big array of Active Record objects (not a great idea, but done for demonstration purposes), and serializing the array of Active Record objects.
    We can then profile this code to see where memory allocations are happening:

    # profile.rb
    require "memory_profiler"
    require_relative "./people"
    report = MemoryProfiler.report do
      run(1000)
    end
    report.pretty_print(to_file: "profile.txt")
    

    Note that the number being fed to run here is 1/10 of the previous example, since the profiler itself uses a lot of memory, and can actually lead to memory exhaustion when profiling code that already causes high memory usage.
    The results file is rather lengthy and includes memory and object allocation and retention at the gem, file, and location levels. There’s a wealth of information to explore, but here are a couple of interesting snippets:

    allocated memory by gem
    -----------------------------------
      17520444  activerecord-4.2.6
       7305511  activesupport-4.2.6
       2551797  activemodel-4.2.6
       2171660  arel-6.0.3
       2002249  sqlite3-1.3.11
    ...
    allocated memory by file
    -----------------------------------
       2840000  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activesupport-4.2.6/lib/activ
    e_support/hash_with_indifferent_access.rb
       2006169  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active
    _record/type/time_value.rb
       2001914  /Users/bruz/code/mem_test/people.rb
       1655493  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active
    _record/connection_adapters/sqlite3_adapter.rb
       1628392  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activesupport-4.2.6/lib/activ
    e_support/json/encoding.rb
    

    We see the most allocations happening inside Active Record, which would seem to point at either instantiating all the objects in the records array, or serialization with #to_json. Next, we can test our memory usage without the profiler while disabling these suspects. We can’t disable retrieving records and still be able to do the serialization step, so let’s try disabling serialization first.

      # File.open("people.txt", "w") { |out| out << records.to_json }
    

    Result:

    $ ruby before_and_after.rb 10000
    Before: 36 MB
    After: 47 MB
    

    That does indeed seem to be where most of the memory is going, with before/after memory delta dropping 81% by skipping it. We can also see what happens if we stop forcing the big array of records to be created.

      # records = Person.all.to_a
      records = Person.all
      # File.open("people.txt", "w") { |out| out << records.to_json }
    

    Result:

    $ ruby before_and_after.rb 10000
    Before: 36 MB
    After: 40 MB
    

    This reduces memory usage as well, although it’s an order of magnitude less reduction than disabling serialization. So at this point, we know our biggest culprits, and can make a decision about what to optimize based on this data.
    Although the example here was contrived, the approaches are generally applicable. Profiler results may not point you at the exact spot in your code where the problem lies, and can also be misinterpreted, so it’s a good idea to follow up by looking at actual memory usage while turning sections of code on and off. Next, we’ll look at some common cases where memory usage becomes an issue and how to optimize them.

    Deserialization

    A common source of memory issues is deserializing large amounts of data from XML, JSON or some other data serialization format. Using methods like JSON.parse or Active Support’s Hash.from_xml is incredibly convenient, but when the data you’re loading is large, the resulting data structure that’s loaded in memory can be enormous.
    If you have control over the source of the data, you can do things to limit the amount of data you’re receiving, like adding filtering or pagination support. But if it’s an external source or one you can’t control, another option is to use a streaming deserializer. For XML, Ox is one option, and for JSON yajl-ruby appears to operate similarly, although I don’t have much experience with it.

    Just because you have limited memory doesn’t mean you cannot parse large XML or JSON documents safely. Streaming deserializers allow you to incrementally extract whatever you need from these documents and still keep the memory footprint low.

    Here’s an example of parsing a 1.7MB XML file, using Hash#from_xml.

    # parse_with_from_xml.rb
    require_relative "./common"
    print_usage_before_and_after do
      # From https://www.cs.washington.edu/research/xmldatasets/data/mondial/mondial-3.0.xml
      file = File.open(File.expand_path("../mondial-3.0.xml", __FILE__))
      hash = Hash.from_xml(file)["mondial"]["continent"]
      puts hash.map { |c| c["name"] }.join(", ")
    end
    
    $ ruby parse_with_from_xml.rb
    Before - MEMORY USAGE(MB): 37
    Europe, Asia, America, Australia/Oceania, Africa
    After - MEMORY USAGE(MB): 164
    

    111MB for a 1.7MB file! This clearly is not going to scale up well. Here’s the streaming parser version.

    # parse_with_ox.rb
    require_relative "./common"
    require "ox"
    class Handler < ::Ox::Sax
      def initialize(&block)
        @yield_to = block
      end
      def start_element(name)
        case name
        when :continent
          @in_continent = true
        end
      end
      def end_element(name)
        case name
        when :continent
          @yield_to.call(@name) if @name
          @in_continent = false
          @name = nil
        end
      end
      def attr(name, value)
        case name
        when :name
          @name = value if @in_continent
        end
      end
    end
    print_usage_before_and_after do
      # From https://www.cs.washington.edu/research/xmldatasets/data/mondial/mondial-3.0.xml
      file = File.open(File.expand_path("../mondial-3.0.xml", __FILE__))
      continents = []
      handler = Handler.new do |continent|
        continents << continent
      end
      Ox.sax_parse(handler, file)
      puts continents.join(", ")
    end
    
    $ ruby parse_with_ox.rb
    Before - MEMORY USAGE(MB): 37
    Europe, Asia, America, Australia/Oceania, Africa
    After - MEMORY USAGE(MB): 37
    

    This brings us down to a negligible memory increase and should be able to handle vastly larger files. However, the tradeoff is that we now have 28 lines of handler code we didn’t need before, which seems like it’d be error prone, and for production use it should have some tests around it.

    Serialization

    As we saw in the section about isolating memory usage hotspots, serialization can have high memory costs. Here’s the key part of people.rb from earlier.

    # to_json.rb
    require_relative "./common"
    print_usage_before_and_after do
      File.open("people.txt", "w") { |out| out << Person.all.to_json }
    end
    

    Running this with 100,000 records in the database, we get:

    $ ruby to_json.rb
    Before: 36 MB
    After: 505 MB
    

    The issue with calling #to_json here is that it instantiates an object for every record, and then encodes to JSON. Generating the JSON record-by-record so that only one record object would need to exist at a time reduces the memory usage significantly. None of the popular Ruby JSON libraries appear to handle this, but a commonly recommended approach is to build the JSON string manually. There is a json-write-stream gem that provides a nice API for doing this, and converting our example to this looks like:

    # json_stream.rb
    require_relative "./common"
    require "json-write-stream"
    print_usage_before_and_after do
      file = File.open("people.txt", "w")
      JsonWriteStream.from_stream(file) do |writer|
        writer.write_object do |obj_writer|
          obj_writer.write_array("people") do |arr_writer|
            Person.find_each do |people|
              arr_writer.write_element people.as_json
            end
          end
        end
      end
    end
    

    Once again, we see optimization has given us more code, but the result seems worth it:

    $ ruby json_stream.rb
    Before: 36 MB
    After: 56 MB
    

    Being Lazy

    A great feature added to Ruby starting with 2.0 is the ability to make enumerators lazy. This is great for improving memory usage when chaining methods on an enumerator. Let’s start with some code that isn’t lazy:

    # not_lazy.rb
    require_relative "./common"
    number = ARGV.shift.to_i
    print_usage_before_and_after do
      names = number.times
                    .map { random_name }
                    .map { |name| name.capitalize }
                    .map { |name| "#{ name } Jr." }
                    .select { |name| name[0] == "X" }
                    .to_a
    end
    

    Result:

    $ ruby not_lazy.rb 1_000_000
    Before: 36 MB
    After: 546 MB
    


    What happens here is that at each step in the chain, it iterates over every element in the enumerator, producing an array that has the subsequent method in the chain invoked on it, and so forth. Let’s see what happens when we make this lazy, which just requires adding a call to lazy on the enumerator we get from times:

    # lazy.rb
    require_relative "./common"
    number = ARGV.shift.to_i
    print_usage_before_and_after do
      names = number.times.lazy
                    .map { random_name }
                    .map { |name| name.capitalize }
                    .map { |name| "#{ name } Jr." }
                    .select { |name| name[0] == "X" }
                    .to_a
    end
    

    Result:

    $ ruby lazy.rb 1_000_000
    Before: 36 MB
    After: 52 MB
    

    Finally, an example that gives us a huge memory usage win, without adding a lot of extra code! Note that if we didn’t need to accumulate any results at the end, for instance, if each item was saved to the database and could then be forgotten, there would be even less memory usage. To make a lazy enumerable evaluate at the end of the chain, just add a final call to force.
    Another thing to note about the example is that the chain starts with a call to times prior to lazy, which uses very little memory since it just returns an enumerator that will generate an integer each time it’s invoked. So if an enumerable can be used instead of a big array at the beginning of the chain, that will help.

    Keeping everything in huge arrays and maps is convenient, but in real world scenarios, you rarely need to do that.

    One real-world application of building an enumerable to lazily feed into some sort of processing pipeline is processing paginated data. So rather than requesting all the pages and putting them into one big array, they could be exposed through an enumerator that nicely hides all the pagination details. This could look something like:

    def records
      Enumerator.new do |yielder|
        has_more = true
        page = 1
        while has_more
          response = fetch(page)
          response.records.each { |record| yielder << record }
          page += 1
          has_more = response.has_more
        end
      end
    end
    

    Conclusion

    We’ve done some characterization of memory usage in Ruby, and looked at some general tools for tracking down memory issues, as well as some common cases and ways to improve them. The common cases we explored are by no means comprehensive and are highly biased by the sort of issues I personally have encountered. However, the biggest gain may just be getting in the mindset of thinking about how the code will impact memory usage.
    This post originally appeared in the Toptal Engineering blog

  • Introduction to Kotlin: Android Programming For Humans

    In a perfect Android world, the main language of Java is really modern, clear, and elegant. You can write less by doing more, and whenever a new feature appears, developers can use it just by increasing version in Gradle. Then while creating a very nice app, it appears fully testable, extensible, and maintainable. Our activities are not too large and complicated, we can change data sources from database to web without tons of differences, and so on. Sounds great, right? Unfortunately, the Android world isn’t this ideal. Google is still striving for perfection, but we all know that ideal worlds don’t exist. Thus, we have to help ourselves in that great journey in the Android world.
    Can Kotlin replace Java?

    What Is Kotlin, and Why Should You Use It?

    So, the first language. I think that Java isn’t the master of elegance or clarity, and it is neither modern nor expressive (and I’m guessing you agree). The disadvantage is that below Android N, we are still limited to Java 6 (including some small parts of Java 7). Developers can also attach RetroLambda to use lambda expressions in their code, which is very useful while using RxJava. Above Android N, we can use some of Java 8’s new functionalities, but it’s still that old, heavy Java. Very often I hear Android developers say “I wish Android supported a nicer language, like iOS does with Swift”. And what if I told you that you can use a very nice, simple language, with null safety, lambdas, and many other nice new features? Welcome to Kotlin.

    What is Kotlin?

    Kotlin is a new language (sometimes referred to as Swift for Android), developed by the JetBrains team, and is now in its 1.0.2 version. What makes it useful in Android development is that it compiles to JVM bytecode, and can be also compiled to JavaScript. It is fully compatible with Java, and Kotlin code can be simply converted to Java code and vice versa (there is a plugin from JetBrains). That means Kotlin can use any framework, library etc. written in Java. On Android, it integrates by Gradle. If you have an existing Android app and you want to implement a new feature in Kotlin without rewriting the whole app, just start writing in Kotlin, and it will work.
    But what are the ‘great new features’? Let me list a few:

    Optional and Named Function Parameters

    fun createDate(day: Int, month: Int, year: Int, hour: Int = 0, minute: Int = 0, second: Int = 0) {
       print("TEST", "$day-$month-$year $hour:$minute:$second")
    }
    

    We Can Call Method createDate in Different Ways

    createDate(1,2,2016) prints:  ‘1-2-2016 0:0:0’
    createDate(1,2,2016, 12) prints: ‘1-2-2016 12:0:0’
    createDate(1,2,2016, minute = 30) prints: ‘1-2-2016 0:30:0’
    

    Null Safety

    If a variable can be null, code will not compile unless we force them to make it. The following code will have an error – nullableVar may be null:

    var nullableVar: String? = “”;
    nullableVar.length;
    

    To compile, we have to check if it’s not null:

    if(nullableVar){
    	nullableVar.length
    }
    

    Or, shorter:

    nullableVar?.length
    

    This way, if nullableVar is null, nothing happens. Otherwise, we can mark variable as not nullable, without a question mark after type:

    var nonNullableVar: String = “”;
    nonNullableVar.length;
    

    This code compiles, and if we want to assign null to nonNullableVar, compiler will show an error.
    There is also very useful Elvis operator:

    var stringLength = nullableVar?.length ?: 0
    

    Then, when nullableVar is null (so nullableVar?.length returns null), stringLength will have value 0.

    Mutable and Immutable Variables

    In the example above, I use var when defining a variable. This is mutable, we can reassign it whenever we want. If we want that variable to be immutable (in many cases we should), we use val (as value, not variable):

    val immutable: Int = 1
    

    After that, the compiler will not allow us to reassign to immutable.

    Lambdas

    We all know what a lambda is, so here I will just show how we can use it in Kotlin:

    button.setOnClickListener({ view -> Log.d("Kotlin","Click")})
    

    Or if the function is the only or last argument:

    button.setOnClickListener { Log.d("Kotlin","Click")}
    

    Extensions

    Extensions are a very helpful language feature, thanks to which we can “extend” existing classes, even when they are final or we don’t have access to their source code.
    For example, to get a string value from edit text, instead of writing every time editText.text.toString() we can write the function:

    fun EditText.textValue(): String{
       return text.toString()
    }
    

    Or shorter:

    fun EditText.textValue() = text.toString()
    

    And now, with every instance of EditText:

    editText.textValue()
    

    Or, we can add a property returning the same:

    var EditText.textValue: String
       get() = text.toString()
       set(v) {setText(v)}
    

    Operator Overloading

    Sometimes useful if we want to add, multiply, or compare objects. Kotlin allows overloading of binary operators (plus, minus, plusAssign, range, etc.), array operators ( get, set, get range, set range), and equals and unary operations (+a, -a, etc.)

    Data Class

    How many lines of code do you need to implement a User class in Java with three properties: copy, equals, hashCode, and toString? In Kaotlin you need only one line:

    data class User(val name: String, val surname: String, val age: Int)
    

    This data class provides equals(), hashCode() and copy() methods, and also toString(), which prints User as:

    User(name=John, surname=Doe, age=23)
    

    Data classes also provide some other useful functions and properties, which you can see in Kotlin documentation.

    Anko Extensions

    You use Butterknife or Android extensions, don’t you? What if you don’t need to even use this library, and after declaring views in XML just use it from code by its ID (like with XAML in C#):

    <Button
            android:id="@+id/loginBtn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    
    loginBtn.setOnClickListener{}
    

    Kotlin has very useful Anko extensions, and with this you don’t need to tell your activity what is loginBtn, it knows it just by “importing” xml:

    import kotlinx.android.synthetic.main.activity_main.*
    

    There are many other useful things in Anko, including starting activities, showing toasts, and so on. This is not the main goal of Anko – it is designed for easily creating layouts from code. So if you need to create a layout programmatically, this is the best way.
    This is only a short view of Kotlin. I recommend reading Antonio Leiva’s blog and his book – Kotlin for Android Developers, and of course the official Kotlin site.

    What Is MVP and Why?

    A nice, powerful, and clear language is not enough. It’s very easy to write messy apps with every language without good architecture. Android developers (mostly ones who are getting started, but also more advanced ones) often give Activity responsibility for everything around them. Activity (or Fragment, or other view) downloads data, sends to save, presents them, responds to user interactions, edits data, manages all child views . . . and often much more. It’s too much for such unstable objects like Activities or Fragments (it’s enough to rotate the screen and Activity says ‘Goodbye….’).
    A very good idea is to isolate responsibilities from views and make them as stupid as possible. Views (Activities, Fragments, custom views, or whatever presents data on screen) should be only responsible for managing their subviews. Views should have presenters, who will communicate with model, and tell them what they should do. This, in short, is the Model-View-Presenter pattern (for me, it should be named Model-Presenter-View to show connections between layers).
    MVC vs MVP
    “Hey, I know something like that, and it’s called MVC!” – didn’t you think? No, MVP is not the same as MVC. In the MVC pattern, your view can communicate with model. While using MVP, you don’t allow any communication between these two layers – the only way View can communicate with Model is through Presenter. The only thing that View knows about Model can be the data structure. View knows how to, for example, display User, but doesn’t know when. Here’s a simple example:
    View knows “I’m Activity, I have two EditTexts and one Button. When somebody clicks the button, I should tell it to my presenter, and pass him EditTexts’ values. And that’s all, I can sleep until next click or presenter tells me what to do.”
    Presenter knows that somewhere is a View, and he knows what operations this View can perform. He also knows that when he receives two strings, he should create User from these two strings and send data to model to save, and if save is successful, tell the view ‘Show success info’.
    Model just knows where data is, where they should be saved, and what operations should be performed on the data.
    Applications written in MVP are easy to test, maintain, and reuse. A pure presenter should know nothing about the Android platform. It should be pure Java (or Kotlin, in our case) class. Thanks to this we can reuse our presenter in other projects. We can also easily write unit tests, testing separately Model, View and Presenter.

    MVP pattern leads to better, less complex codebase by keeping user interface and business logic truly separate.

    A little digression: MVP should be a part of Uncle Bob’s Clean Architecture to make applications even more flexible and nicely architectured. I’ll try to write about that next time.

    Sample App with MVP and Kotlin

    That’s enough theory, let’s see some code! Okay, let’s try to create a simple app. The main goal for this app is to create user. First screen will have two EditTexts (Name and Surname) and one Button (Save). After entering name and surname and clicking ‘Save’, the app should show ‘User is saved’ and go to the next screen, where saved name and surname is presented. When name or surname is empty, the app should not save user and show an error indicating what’s wrong.
    The first thing after creating Android Studio project is to configure Kotlin. You should install Kotlin plugin, and, after restart, in Tools > Kotlin you can click ‘Configure Kotlin in Project’. IDE will add Kotlin dependencies to Gradle. If you have any existing code, you can easily convert it to Kotlin by (Ctrl+Shift+Alt+K or Code > Convert Java file to Kotlin). If something is wrong and the project does not compile, or Gradle does not see Kotlin, you can check code of the app available on GitHub.

    Kotlin not only interoperates well with Java frameworks and libraries, it allows you to continue using most of the same tools that you are already familiar with.

    Now that we have a project, let’s start by creating our first view – CreateUserView. This view should have the functionalities mentioned earlier, so we can write an interface for that:

    interface CreateUserView : View {
       fun showEmptyNameError() /* show error when name is empty */
       fun showEmptySurnameError() /* show error when surname is empty */
       fun showUserSaved() /* show user saved info */
       fun showUserDetails(user: User) /* show user details */
    }
    

    As you can see, Kotlin is similar to Java in declaring functions. All of those are functions that return nothing, and the last have one parameter. This is the difference, parameter type comes after name. The View interface is not from Android – it’s our simple, empty interface:

    interface View
    

    Basic Presenter’s interface should have a property of View type, and at least on method (onDestroy for example), where this property will be set to null:

    interface Presenter<T : View> {
       var view: T?
       fun onDestroy(){
           view = null
       }
    }
    

    Here you can see another Kotlin feature – you can declare properties in interfaces, and also implement methods there.
    Our CreateUserView needs to communicate with CreateUserPresenter. The only additional function that this Presenter needs is saveUser with two string arguments:

    interface CreateUserPresenter<T : View>: Presenter<T> {
       fun saveUser(name: String, surname: String)
    }
    

    We also need Model definition – it’s mentioned earlier data class:

    data class User(val name: String, val surname: String)
    

    After declaring all interfaces, we can start implementing.
    CreateUserPresenter will be implemented in CreateUserPresenterImpl:

    class CreateUserPresenterImpl(override var view: CreateUserView?): CreateUserPresenter<CreateUserView> {
       override fun saveUser(name: String, surname: String) {
       }
    }
    

    The first line, with class definition:

    CreateUserPresenterImpl(override var view: CreateUserView?)
    

    Is a constructor, we use it for assigning view property, defined in interface.
    MainActivity, which is our CreateUserView implementation, needs a reference to CreateUserPresenter:

    class MainActivity : AppCompatActivity(), CreateUserView {
       private val presenter: CreateUserPresenter<CreateUserView> by lazy {
           CreateUserPresenterImpl(this)
       }
       override fun onCreate(savedInstanceState: Bundle?) {
           super.onCreate(savedInstanceState)
           setContentView(R.layout.activity_main)
           saveUserBtn.setOnClickListener{
               presenter.saveUser(userName.textValue(), userSurname.textValue()) /*use of textValue() extension, mentioned earlier */
           }
       }
       override fun showEmptyNameError() {
           userName.error = getString(R.string.name_empty_error) /* it's equal to userName.setError() - Kotlin allows us to use property */
       }
       override fun showEmptySurnameError() {
           userSurname.error = getString(R.string.surname_empty_error)
       }
       override fun showUserSaved() {
           toast(R.string.user_saved) /* anko extension - equal to Toast.makeText(this, R.string.user_saved, Toast.LENGTH_LONG) */
       }
       override fun showUserDetails(user: User) {
       }
    override fun onDestroy() {
       presenter.onDestroy()
    }
    }
    

    At the beginning of the class, we defined our presenter:

    private val presenter: CreateUserPresenter<CreateUserView> by lazy {
           CreateUserPresenterImpl(this)
    }
    

    It is defined as immutable (val), and is created by lazy delegate, which will be assigned the first time it is needed. Moreover, we are sure that it will not be null (no question mark after definition).
    When the User clicks on the Save button, View sends information to Presenter with EditTexts values. When that happens, User should be saved, so we have to implement saveUser method in Presenter (and some of the Model’s functions):

    override fun saveUser(name: String, surname: String) {
       val user = User(name, surname)
       when(UserValidator.validateUser(user)){
           UserError.EMPTY_NAME -> view?.showEmptyNameError()
           UserError.EMPTY_SURNAME -> view?.showEmptySurnameError()
           UserError.NO_ERROR -> {
               UserStore.saveUser(user)
    view?.showUserSaved()
               view?.showUserDetails(user)
           }
       }
    }
    

    When a User is created, it is sent to UserValidator to check for validity. Then, according to the result of validation, proper method is called. The when() {} construct is same as switch/case in Java. But it is more powerful – Kotlin allows use of not only enum or int in ‘case’, but also ranges, strings or object types. It must contain all possibilities or have an else expression. Here, it covers all UserError values.
    By using view?.showEmptyNameError() (with a question mark after view), we are protected from NullPointer. View can be nulled in onDestroy method, and with this construction, nothing will happen.
    When a User model has no errors, it tells UserStore to save it, and then instruct View to show success and show details.
    As mentioned earlier, we have to implement some model things:

    enum class UserError {
       EMPTY_NAME,
       EMPTY_SURNAME,
       NO_ERROR
    }
    object UserStore {
       fun saveUser(user: User){
           //Save user somewhere: Database, SharedPreferences, send to web...
       }
    }
    object UserValidator {
       fun validateUser(user: User): UserError {
           with(user){
               if(name.isNullOrEmpty()) return UserError.EMPTY_NAME
               if(surname.isNullOrEmpty()) return UserError.EMPTY_SURNAME
           }
           return UserError.NO_ERROR
       }
    }
    

    The most interesting thing here is UserValidator. By using the object word, we can create a singleton class, with no worries about threads, private constructors and so on.
    Next thing – in validateUser(user) method, there is with(user) {} expression. Code within such block is executed in context of object, passed in with name and surname are User’s properties.
    There is also another little thing. All above code, from enum to UserValidator, definition is placed in one file (definition of User class is also here). Kotlin does not force you to have each public class in single file (or name class exactly as file). Thus, if you have some short pieces of related code (data classes, extensions, functions, constants – Kotlin doesn’t require class for function or constant), you can place it in one single file instead of spreading through all files in project.
    When a user is saved, our app should display that. We need another View – it can be any Android view, custom View, Fragment or Activity. I chose Activity.
    So, let’s define UserDetailsView interface. It can show user, but it should also show an error when user is not present:

    interface UserDetailsView {
       fun showUserDetails(user: User)
       fun showNoUserError()
    }
    

    Next, UserDetailsPresenter. It should have a user property:

    interface UserDetailsPresenter<T: View>: Presenter<T> {
       var user: User?
    }
    

    This interface will be implemented in UserDetailsPresenterImpl. It has to override user property. Every time this property is assigned, user should be refreshed on the view. We can use a property setter for this:

    class UserDetailsPresenterImpl(override var view: UserDetailsView?): UserDetailsPresenter<UserDetailsView> {
       override var user: User? = null
           set(value) {
               field = value
               if(field != null){
                   view?.showUserDetails(field!!)
               } else {
                   view?.showNoUserError()
               }
           }
    }
    

    UserDetailsView implementation, UserDetailsActivity, is very simple. Just like before, we have a presenter object created by lazy loading. User to display should be passed via intent. There is one little problem with this for now, and we will solve it in a moment. When we have user from intent, View needs to assign it to their presenter. After that, user will be refreshed on the screen, or, if it is null, the error will appear (and activity will finish – but presenter doesn’t know about that):

    class UserDetailsActivity: AppCompatActivity(), UserDetailsView {
       private val presenter: UserDetailsPresenter<UserDetailsView> by lazy {
           UserDetailsPresenterImpl(this)
       }
       override fun onCreate(savedInstanceState: Bundle?) {
           super.onCreate(savedInstanceState)
           setContentView(R.layout.activity_user_details)
           val user = intent.getParcelableExtra<User>(USER_KEY)
           presenter.user = user
       }
       override fun showUserDetails(user: User) {
           userFullName.text = "${user.name} ${user.surname}"
       }
       override fun showNoUserError() {
           toast(R.string.no_user_error)
           finish()
       }
    override fun onDestroy() {
       presenter.onDestroy()
    }
    }
    

    Passing objects via intents requires that this object implements Parcelable interface. This is very ‘dirty’ work. Personally, I hate doing this because of all of the CREATORs, properties, saving, restoring, and so on. Fortunately, there is proper plugin, Parcelable for Kotlin. After installing it, we can generate Parcelable just with one click.
    The last thing to do is to implement showUserDetails(user: User) in our MainActivity:

    override fun showUserDetails(user: User) {
       startActivity<UserDetailsActivity>(USER_KEY to user) /* anko extension - starts UserDetailsActivity and pass user as USER_KEY in intent */
    }
    

    And that’s all.
    Demo Android app in Kotlin
    We have a simple app that saves a User (actually, it is not saved, but we can add this functionality without touching presenter or view) and presents it on the screen. In the future, if we want to change the way user is presented on the screen, such as from two activities to two fragments in one activity, or two custom views, changes will be only in View classes. Of course, if we don’t change functionality or model’s structure. Presenter, who doesn’t know what exactly View is, won’t need any changes.

    What’s Next?

    In our app, Presenter is created every time an activity is created. This approach, or its opposite, if Presenter should persist across activity instances, is a subject of much discussion across the Internet. For me, it depends on the app, its needs, and the developer. Sometimes it’s better is to destroy presenter, sometimes not. If you decide to persist one, a very interesting technique is to use LoaderManager for that.
    As mentioned before, MVP should be a part of Uncle Bob’s Clean architecture. Moreover, good developers should use Dagger to inject presenters dependencies to activities. It also helps maintain, test, and reuse code in future. Currently, Kotlin works very well with Dagger (before the official release it wasn’t so easy), and also with other helpful Android libraries.

    Wrap Up

    For me, Kotlin is a great language. It’s modern, clear, and expressive while still being developed by great people. And we can use any new release on any Android device and version. Whatever makes me angry at Java, Kotlin improves.
    Of course, as I said nothing is ideal. Kotlin also have some disadvantages. The newest gradle plugin versions (mainly from alpha or beta) don’t work well with this language. Many people complain that build time is a bit longer than pure Java, and apks have some additional MB’s. But Android Studio and Gradle are still improving, and phones have more and more space for apps. That’s why I believe Kotlin can be a very nice language for every Android developer. Just give it a try, and share in the comments section below what you think.
    Source code of the sample app is available on Github: github.com/tomaszczura/AndroidMVPKotlin
    This post originally appeared in Toptal 

  • Hunting Down Memory Issues In Ruby: A Definitive Guide

    I’m sure there are some lucky Ruby developers out there who will never run into issues with memory, but for the rest of us, it’s incredibly challenging to hunt down where memory usage is getting out of hand and fix it. Fortunately, if you’re using a modern Ruby (2.1+), there are some great tools and techniques available for dealing with common issues. It could also be said that memory optimization can be fun and rewarding although I may be alone in that sentiment.
    Hunting Down Memory Issues In Ruby

    If you thought bugs were pesky, wait until you hunt for memory issues.

    As with all forms of optimization, odds are that it will add code complexity, so it’s not worth doing unless there are measurable and significant gains.
    Everything described here is done using the canonical MRI Ruby, version 2.2.4, although other 2.1+ versions should behave similarly.

    It’s Not a Memory Leak!

    When a memory issue is discovered, it’s easy to jump to the conclusion that there’s a memory leak. For example, in a web application, you may see that after you spin up your server, repeated calls to the same endpoint keep driving memory usage up higher with each request. There are certainly cases where legitimate memory leaks happen, but I’d wager they are vastly outnumbered by memory issues with this same appearance that aren’t actually leaks.
    As a (contrived) example, let’s look at a bit of Ruby code that repeatedly builds a big array of hashes and discards it. First, here’s some code that’ll be shared throughout the examples in this post:

    # common.rb
    require "active_record"
    require "active_support/all"
    require "get_process_mem"
    require "sqlite3"
    ActiveRecord::Base.establish_connection(
      adapter: "sqlite3",
      database: "people.sqlite3"
    )
    class Person < ActiveRecord::Base; end
    def print_usage(description)
      mb = GetProcessMem.new.mb
      puts "#{ description } - MEMORY USAGE(MB): #{ mb.round }"
    end
    def print_usage_before_and_after
      print_usage("Before")
      yield
      print_usage("After")
    end
    def random_name
      (0...20).map { (97 + rand(26)).chr }.join
    end
    

    And the array builder:

    # build_arrays.rb
    require_relative "./common"
    ARRAY_SIZE = 1_000_000
    times = ARGV.first.to_i
    print_usage(0)
    (1..times).each do |n|
      foo = []
      ARRAY_SIZE.times { foo << {some: "stuff"} }
      print_usage(n)
    end
    

    The get_process_mem gem is just a convenient way to get the memory being used by the current Ruby process. What we see is the same behavior that was described above, a continual increase in memory usage.

    $ ruby build_arrays.rb 10
    0 - MEMORY USAGE(MB): 17
    1 - MEMORY USAGE(MB): 330
    2 - MEMORY USAGE(MB): 481
    3 - MEMORY USAGE(MB): 492
    4 - MEMORY USAGE(MB): 559
    5 - MEMORY USAGE(MB): 584
    6 - MEMORY USAGE(MB): 588
    7 - MEMORY USAGE(MB): 591
    8 - MEMORY USAGE(MB): 603
    9 - MEMORY USAGE(MB): 613
    10 - MEMORY USAGE(MB): 621
    

    However, if we run more iterations, we’ll eventually plateau.

    $ ruby build_arrays.rb 40
    0 - MEMORY USAGE(MB): 9
    1 - MEMORY USAGE(MB): 323
    ...
    32 - MEMORY USAGE(MB): 700
    33 - MEMORY USAGE(MB): 699
    34 - MEMORY USAGE(MB): 698
    35 - MEMORY USAGE(MB): 698
    36 - MEMORY USAGE(MB): 696
    37 - MEMORY USAGE(MB): 696
    38 - MEMORY USAGE(MB): 696
    39 - MEMORY USAGE(MB): 701
    40 - MEMORY USAGE(MB): 697
    

    Hitting this plateau is the hallmark of not being an actual memory leak, or that the memory leak is so small that it’s not visible compared to the rest of the memory usage. What may not be intuitive is why memory usage continues to grow after the first iteration. After all, it built a big array, but then promptly discarded it and started building a new one of the same size. Can’t it just use the space freed up by the previous array? The answer, which explains our problem, is no. Aside from tuning the garbage collector, you don’t have control over when it runs, and what we’re seeing in the build_arrays.rb example is new memory allocations being made prior to garbage collection of our old, discarded objects.

    Do not panic if you see a sudden rise in the memory usage of your app. Apps can run out of memory for all sorts of reasons – not just memory leaks.

    I should point out that this isn’t some sort of horrible memory management issue specific to Ruby, but is generally applicable to garbage-collected languages. Just to reassure myself of this, I reproduced essentially the same example with Go and saw similar results. However, there are Ruby libraries that make it easy to create this sort of memory issue.

    Divide and Conquer

    So if we need to work with large chunks of data, are we doomed to just throw lots of RAM at our problem? Thankfully, that’s not the case. If we take the build_arrays.rb example and decrease the array size, we’ll see a decrease in the point where memory usage plateaus that’s roughly proportional to the array size.

    This means that if we can break our work into smaller pieces to process and avoid having too many objects existing at one time, we can dramatically reduce the memory footprint. Unfortunately, that often means taking nice, clean code and turning it into more code that does the same thing, just in a more memory-efficient way.

    Isolating Memory Usage Hotspots

    In a real codebase, the source of a memory issue will likely not be as obvious as in the build_arrays.rbexample. Isolating a memory issue before trying to actually dig in and fix it is essential because it’s easy to make incorrect assumptions about what’s causing the problem.

    I generally use two approaches, often in combination, to track down memory issues: leaving the code intact and wrapping a profiler around it, and monitoring memory usage of the process while disabling/enabling different parts of the code I suspect could be problematic. I’ll be using memory_profiler here for profiling, butruby-prof is another popular option, and derailed_benchmarks has some great Rails-specific capabilities.
    Here’s some code that’ll use a bunch of memory, where it may not be immediately clear which step is pushing up memory usage the most:

    # people.rb
    require_relative "./common"
    def run(number)
      Person.delete_all
      names = number.times.map { random_name }
      names.each do |name|
        Person.create(name: name)
      end
      records = Person.all.to_a
      File.open("people.txt", "w") { |out| out << records.to_json }
    end
    

    Using get_process_mem, we can quickly verify that it does use a lot of memory when there are a lot of Person records being created.

    # before_and_after.rb
    require_relative "./people"
    print_usage_before_and_after do
      run(ARGV.shift.to_i)
    end
    

    Result:

    $ ruby before_and_after.rb 10000
    Before - MEMORY USAGE(MB): 37
    After - MEMORY USAGE(MB): 96
    

    Looking through the code, there are multiple steps that seem like good candidates for using a lot of memory: building a big array of strings, calling #to_a on an Active Record relation to make a big array of Active Record objects (not a great idea, but done for demonstration purposes), and serializing the array of Active Record objects.
    We can then profile this code to see where memory allocations are happening:

    # profile.rb
    require "memory_profiler"
    require_relative "./people"
    report = MemoryProfiler.report do
      run(1000)
    end
    report.pretty_print(to_file: "profile.txt")
    

    Note that the number being fed to run here is 1/10 of the previous example, since the profiler itself uses a lot of memory, and can actually lead to memory exhaustion when profiling code that already causes high memory usage.
    The results file is rather lengthy and includes memory and object allocation and retention at the gem, file, and location levels. There’s a wealth of information to explore, but here are a couple of interesting snippets:

    allocated memory by gem
    -----------------------------------
      17520444  activerecord-4.2.6
       7305511  activesupport-4.2.6
       2551797  activemodel-4.2.6
       2171660  arel-6.0.3
       2002249  sqlite3-1.3.11
    ...
    allocated memory by file
    -----------------------------------
       2840000  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activesupport-4.2.6/lib/activ
    e_support/hash_with_indifferent_access.rb
       2006169  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active
    _record/type/time_value.rb
       2001914  /Users/bruz/code/mem_test/people.rb
       1655493  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active
    _record/connection_adapters/sqlite3_adapter.rb
       1628392  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activesupport-4.2.6/lib/activ
    e_support/json/encoding.rb
    

    We see the most allocations happening inside Active Record, which would seem to point at either instantiating all the objects in the records array, or serialization with #to_json. Next, we can test our memory usage without the profiler while disabling these suspects. We can’t disable retrieving records and still be able to do the serialization step, so let’s try disabling serialization first.

      # File.open("people.txt", "w") { |out| out << records.to_json }
    

    Result:

    $ ruby before_and_after.rb 10000
    Before: 36 MB
    After: 47 MB
    

    That does indeed seem to be where most of the memory is going, with before/after memory delta dropping 81% by skipping it. We can also see what happens if we stop forcing the big array of records to be created.

      # records = Person.all.to_a
      records = Person.all
      # File.open("people.txt", "w") { |out| out << records.to_json }
    

    Result:

    $ ruby before_and_after.rb 10000
    Before: 36 MB
    After: 40 MB
    

    This reduces memory usage as well, although it’s an order of magnitude less reduction than disabling serialization. So at this point, we know our biggest culprits, and can make a decision about what to optimize based on this data.
    Although the example here was contrived, the approaches are generally applicable. Profiler results may not point you at the exact spot in your code where the problem lies, and can also be misinterpreted, so it’s a good idea to follow up by looking at actual memory usage while turning sections of code on and off. Next, we’ll look at some common cases where memory usage becomes an issue and how to optimize them.

    Deserialization

    A common source of memory issues is deserializing large amounts of data from XML, JSON or some other data serialization format. Using methods like JSON.parse or Active Support’s Hash.from_xml is incredibly convenient, but when the data you’re loading is large, the resulting data structure that’s loaded in memory can be enormous.
    If you have control over the source of the data, you can do things to limit the amount of data you’re receiving, like adding filtering or pagination support. But if it’s an external source or one you can’t control, another option is to use a streaming deserializer. For XML, Ox is one option, and for JSON yajl-ruby appears to operate similarly, although I don’t have much experience with it.

    Just because you have limited memory doesn’t mean you cannot parse large XML or JSON documents safely. Streaming deserializers allow you to incrementally extract whatever you need from these documents and still keep the memory footprint low.

    Here’s an example of parsing a 1.7MB XML file, using Hash#from_xml.

    # parse_with_from_xml.rb
    require_relative "./common"
    print_usage_before_and_after do
      # From https://www.cs.washington.edu/research/xmldatasets/data/mondial/mondial-3.0.xml
      file = File.open(File.expand_path("../mondial-3.0.xml", __FILE__))
      hash = Hash.from_xml(file)["mondial"]["continent"]
      puts hash.map { |c| c["name"] }.join(", ")
    end
    
    $ ruby parse_with_from_xml.rb
    Before - MEMORY USAGE(MB): 37
    Europe, Asia, America, Australia/Oceania, Africa
    After - MEMORY USAGE(MB): 164
    

    111MB for a 1.7MB file! This clearly is not going to scale up well. Here’s the streaming parser version.

    # parse_with_ox.rb
    require_relative "./common"
    require "ox"
    class Handler < ::Ox::Sax
      def initialize(&block)
        @yield_to = block
      end
      def start_element(name)
        case name
        when :continent
          @in_continent = true
        end
      end
      def end_element(name)
        case name
        when :continent
          @yield_to.call(@name) if @name
          @in_continent = false
          @name = nil
        end
      end
      def attr(name, value)
        case name
        when :name
          @name = value if @in_continent
        end
      end
    end
    print_usage_before_and_after do
      # From https://www.cs.washington.edu/research/xmldatasets/data/mondial/mondial-3.0.xml
      file = File.open(File.expand_path("../mondial-3.0.xml", __FILE__))
      continents = []
      handler = Handler.new do |continent|
        continents << continent
      end
      Ox.sax_parse(handler, file)
      puts continents.join(", ")
    end
    
    $ ruby parse_with_ox.rb
    Before - MEMORY USAGE(MB): 37
    Europe, Asia, America, Australia/Oceania, Africa
    After - MEMORY USAGE(MB): 37
    

    This brings us down to a negligible memory increase and should be able to handle vastly larger files. However, the tradeoff is that we now have 28 lines of handler code we didn’t need before, which seems like it’d be error prone, and for production use it should have some tests around it.

    Serialization

    As we saw in the section about isolating memory usage hotspots, serialization can have high memory costs. Here’s the key part of people.rb from earlier.

    # to_json.rb
    require_relative "./common"
    print_usage_before_and_after do
      File.open("people.txt", "w") { |out| out << Person.all.to_json }
    end
    

    Running this with 100,000 records in the database, we get:

    $ ruby to_json.rb
    Before: 36 MB
    After: 505 MB
    

    The issue with calling #to_json here is that it instantiates an object for every record, and then encodes to JSON. Generating the JSON record-by-record so that only one record object would need to exist at a time reduces the memory usage significantly. None of the popular Ruby JSON libraries appear to handle this, but a commonly recommended approach is to build the JSON string manually. There is a json-write-stream gem that provides a nice API for doing this, and converting our example to this looks like:

    # json_stream.rb
    require_relative "./common"
    require "json-write-stream"
    print_usage_before_and_after do
      file = File.open("people.txt", "w")
      JsonWriteStream.from_stream(file) do |writer|
        writer.write_object do |obj_writer|
          obj_writer.write_array("people") do |arr_writer|
            Person.find_each do |people|
              arr_writer.write_element people.as_json
            end
          end
        end
      end
    end
    

    Once again, we see optimization has given us more code, but the result seems worth it:

    $ ruby json_stream.rb
    Before: 36 MB
    After: 56 MB
    

    Being Lazy

    A great feature added to Ruby starting with 2.0 is the ability to make enumerators lazy. This is great for improving memory usage when chaining methods on an enumerator. Let’s start with some code that isn’t lazy:

    # not_lazy.rb
    require_relative "./common"
    number = ARGV.shift.to_i
    print_usage_before_and_after do
      names = number.times
                    .map { random_name }
                    .map { |name| name.capitalize }
                    .map { |name| "#{ name } Jr." }
                    .select { |name| name[0] == "X" }
                    .to_a
    end
    

    Result:

    $ ruby not_lazy.rb 1_000_000
    Before: 36 MB
    After: 546 MB
    


    What happens here is that at each step in the chain, it iterates over every element in the enumerator, producing an array that has the subsequent method in the chain invoked on it, and so forth. Let’s see what happens when we make this lazy, which just requires adding a call to lazy on the enumerator we get from times:

    # lazy.rb
    require_relative "./common"
    number = ARGV.shift.to_i
    print_usage_before_and_after do
      names = number.times.lazy
                    .map { random_name }
                    .map { |name| name.capitalize }
                    .map { |name| "#{ name } Jr." }
                    .select { |name| name[0] == "X" }
                    .to_a
    end
    

    Result:

    $ ruby lazy.rb 1_000_000
    Before: 36 MB
    After: 52 MB
    

    Finally, an example that gives us a huge memory usage win, without adding a lot of extra code! Note that if we didn’t need to accumulate any results at the end, for instance, if each item was saved to the database and could then be forgotten, there would be even less memory usage. To make a lazy enumerable evaluate at the end of the chain, just add a final call to force.
    Another thing to note about the example is that the chain starts with a call to times prior to lazy, which uses very little memory since it just returns an enumerator that will generate an integer each time it’s invoked. So if an enumerable can be used instead of a big array at the beginning of the chain, that will help.

    Keeping everything in huge arrays and maps is convenient, but in real world scenarios, you rarely need to do that.

    One real-world application of building an enumerable to lazily feed into some sort of processing pipeline is processing paginated data. So rather than requesting all the pages and putting them into one big array, they could be exposed through an enumerator that nicely hides all the pagination details. This could look something like:

    def records
      Enumerator.new do |yielder|
        has_more = true
        page = 1
        while has_more
          response = fetch(page)
          response.records.each { |record| yielder record }
          page += 1
          has_more = response.has_more
        end
      end
    end
    

    Conclusion

    We’ve done some characterization of memory usage in Ruby, and looked at some general tools for tracking down memory issues, as well as some common cases and ways to improve them. The common cases we explored are by no means comprehensive and are highly biased by the sort of issues I personally have encountered. However, the biggest gain may just be getting in the mindset of thinking about how the code will impact memory usage.
    This article was written by Bruz Marzolf, a Toptal Ruby developer.

  • Best Safety Apps for Women

    Best Safety Apps for Women

    [pt_text]
    [/pt_text][pt_text]SOS – Stay Safe:
    sos
    This is a free Android App. No needs to type in the phone unlock code, just keep this app activated and shaking it a couple of times (custom metres will trigger alert along with your geographical location to the emergency contact.
    If shaking is confusing, it also features home button tapping, which will also send a message, location, even battery status of phone and an audio recording.

    VithU:
    VithU
    A V Gumrah Initiative this is a real time interactive safety application for women. All you need to do is press the power button of your phone twice and the alert message will be sent to pre-set contacts along with your location.
    This App continues to send the location to contacts every two minutes.

    Raksha – Women Safety Alert:
    Raksha - Women Safety Alert
    The Raksha app is designed to ensure that women stay safe always. The app comes equipped with a button, which will send alerts to your loved ones with your location in a situation of distress. You can select the contacts, which will be able to see your location. Moreover, if the app is switched off and is not working then also you will be able to send alerts by simply pressing the volume key for three seconds.
    The app also has SOS functionality and can also send SMS if stuck in a non-internet area.

    Smart24x7 – Personal Safety App:
    Smart24x7-Personal-Safety-App
    The Smart24x7 app is supported by the various states’ police just to ensure the safety of women and senior citizens. The app sends panic alerts to emergency contacts in a problematic situation. It also records voices and also takes photographs during the panic situation and transfers these to the police as well.
    It also has call centre support, which will track down the primary movements of the user. Users just need to press the panic button and select the type of service required and then finally click on submit.

    Nirbhaya – Be Fearless:
    Nirbhaya Be Fearless
    The app sends an alert to pre-added contacts with the user’s location. The user can choose to send the alert in the form of an SOS message, phone call or a Facebook post.
    The app also provides the user with the option of sending an alert by just shaking their phone in a situation of emergency. It also sends user’s location to chosen contacts every two hours and after 300-meter change in position.

    bSafe – Personal Safety:
    bSafe - Personal Safety
    Let emergency contacts follow you through a live GPS trail; set a timed alarm that goes off if you haven’t ‘checked in’; make your phone ring with a fake call; the alert notifies emergency contacts with location, video, even siren.

    Scream Alarm:
    Scream Alarm
    The application can be used to generate a very high volume scream in times of distress when your own lungs may fail you. The generated scream is in a woman’s voice which is extremely helpful in deterring potential trouble makers
    It screams in a woman’s voice — no more, no less.

    Safetipin:
    Safetipin
    This safety app provides users with features like GPS tracking, directions to safe locations and pins showing safe and unsafe areas on the map.
    Apart from the basic SOS feature of contacting the user’s friends and family in emergency situations and letting them track the users, the app has a number of other features.
    Safetipin is also available in Hindi, Bahasa and Spanish, besides English.

    Shake2Safety:
    Shake2Safety
    The Shake2Safety app is the easiest to use. The user just needs to shake their smartphone or just press the power button four times to send an SOS text or call to the registered numbers. It works with the locked screen on and even without an internet connection.
    Moreover, the users will also have the ability to activate or deactivate the option of shaking the device to send an alert.The app can also be used in case of an accident, harassment, robbery or any natural calamities.

    Women Safety Secured:
    Women-Safety-Secured
    The app recognizes shouting and crying as distress signals and sends text messages to emergency contacts with location.
    [/pt_text]

  • Clean Code and The Art of Exception Handling

    Exceptions are as old as programming itself. Back in the days when programming was done in hardware, or via low-level programming languages, exceptions were used to alter the flow of the program, and to avoid hardware failures. Today, Wikipedia defines exceptions as:

    anomalous or exceptional conditions requiring special processing – often changing the normal flow of program execution…

    And that handling them requires:

    specialized programming language constructs or computer hardware mechanisms.

    So, exceptions require special treatment, and an unhandled exception may cause unexpected behavior. The results are often spectacular. In 1996, the famous Ariane 5 rocket launch failure was attributed to an unhandled overflow exception. History’s Worst Software Bugs contains some other bugs that could be attributed to unhandled or miss-handled exceptions.
    Over time, these errors, and countless others (that were, perhaps, not as dramatic, but still catastrophic for those involved) contributed to the impression that exceptions are bad.
    The results of improperly handling exceptions have led us to believe that exceptions are always bad.
    But exceptions are a fundamental element of modern programming; they exist to make our software better. Rather than fearing exceptions, we should embrace them and learn how to benefit from them. In this article, we will discuss how to manage exceptions elegantly, and use them to write clean code that is more maintainable.

    Exception Handling: It’s a Good Thing

    With the rise of object-oriented programming (OOP), exception support has become a crucial element of modern programming languages. A robust exception handling system is built into most languages, nowadays. For example, Ruby provides for the following typical pattern:

    begin
      do_something_that_might_not_work!
    rescue SpecificError => e
      do_some_specific_error_clean_up
      retry if some_condition_met?
    ensure
      this_will_always_be_executed
    end
    

    There is nothing wrong with the previous code. But overusing these patterns will cause code smells, and won’t necessarily be beneficial. Likewise, misusing them can actually do a lot of harm to your code base, making it brittle, or obfuscating the cause of errors.
    The stigma surrounding exceptions often makes programmers feel at a loss. It’s a fact of life that exceptions can’t be avoided, but we are often taught they must be dealt with swiftly and decisively. As we will see, this is not necessarily true. Rather, we should learn the art of handling exceptions gracefully, making them harmonious with the rest of our code.
    Following are some recommended practices that will help you embrace exceptions and make use of them and their abilities to keep your code maintainable, extensible, and readable:

    • maintainability: Allows us to easily find and fix new bugs, without the fear of breaking current functionality, introducing further bugs, or having to abandon the code altogether due to increased complexity over time.
    • extensibility: Allows us to easily add to our code base, implementing new or changed requirements without breaking existing functionality. Extensibility provides flexibility, and enables a high level of reusability for our code base.
    • readability: Allows us to easily read the code and discover it’s purpose without spending too much time digging. This is critical for efficiently discovering bugs and untested code.

    These elements are the main factors of what we might call cleanliness or quality, which is not a direct measure itself, but instead is the combined effect of the previous points, as demonstrated in this comic:
    "WTFs/m" by Thom Holwerda, OSNews
    With that said, let’s dive into these practices and see how each of them affects those three measures.
    Note: We will present examples from Ruby, but all of the constructs demonstrated here have equivalents in the most common OOP languages.

    Always create your own ApplicationError hierarchy

    Most languages come with a variety of exception classes, organized in an inheritance hierarchy, like any other OOP class. To preserve the readability, maintainability, and extensibility of our code, it’s a good idea to create our own subtree of application-specific exceptions that extend the base exception class. Investing some time in logically structuring this hierarchy can be extremely beneficial. For example:

    class ApplicationError < StandardError; end
    # Validation Errors
    class ValidationError < ApplicationError; end
    class RequiredFieldError < ValidationError; end
    class UniqueFieldError < ValidationError; end
    # HTTP 4XX Response Errors
    class ResponseError < ApplicationError; end
    class BadRequestError < ResponseError; end
    class UnauthorizedError < ResponseError; end
    # ...
    

    Example of an application exception hierarchy.
    Having an extensible, comprehensive exceptions package for our application makes handling these application-specific situations much easier. For example, we can decide which exceptions to handle in a more natural way. This not only boosts the readability of our code, but also increases the maintainability of our applications and libraries (gems).
    From the readability perspective, it’s much easier to read:

    rescue ValidationError => e
    

    Than to read:

    rescue RequiredFieldError, UniqueFieldError, ... => e
    

    From the maintainability perspective, say, for example, we are implementing a JSON API, and we have defined our own ClientError with several subtypes, to be used when a client sends a bad request. If any one of these is raised, the application should render the JSON representation of the error in its response. It will be easier to fix, or add logic, to a single block that handles ClientErrors rather than looping over each possible client error and implementing the same handler code for each. In terms of extensibility, if we later have to implement another type of client error, we can trust it will already be handled properly here.
    Moreover, this does not prevent us from implementing additional special handling for specific client errors earlier in the call stack, or altering the same exception object along the way:

    # app/controller/pseudo_controller.rb
    def authenticate_user!
      fail AuthenticationError if token_invalid? || token_expired?
      User.find_by(authentication_token: token)
    rescue AuthenticationError => e
      report_suspicious_activity if token_invalid?
      raise e
    end
    def show
      authenticate_user!
      show_private_stuff!(params[:id])
    rescue ClientError => e
      render_error(e)
    end
    

    As you can see, raising this specific exception didn’t prevent us from being able to handle it on different levels, altering it, re-raising it, and allowing the parent class handler to resolve it.
    Two things to note here:

    • Not all languages support raising exceptions from within an exception handler.
    • In most languages, raising a new exception from within a handler will cause the original exception to be lost forever, so it’s better to re-raise the same exception object (as in the above example) to avoid losing track of the original cause of the error. (Unless you are doing this intentionally).

    Never rescue Exception

    That is, never try to implement a catch-all handler for the base exception type. Rescuing or catching all exceptions wholesale is never a good idea in any language, whether it’s globally on a base application level, or in a small buried method used only once. We don’t want to rescue Exception because it will obfuscate whatever really happened, damaging both maintainability and extensibility. We can waste a huge amount of time debugging what the actual problem is, when it could be as simple as a syntax error:

    # main.rb
    def bad_example
      i_might_raise_exception!
    rescue Exception
      nah_i_will_always_be_here_for_you
    end
    # elsewhere.rb
    def i_might_raise_exception!
      retrun do_a_lot_of_work!
    end
    

    You might have noticed the error in the previous example; return is mistyped. Although modern editors provide some protection against this specific type of syntax error, this example illustrates how rescue Exception does harm to our code. At no point is the actual type of the exception (in this case a NoMethodError) addressed, nor is it ever exposed to the developer, which may cause us to waste a lot of time running in circles.

    Never rescue more exceptions than you need to

    The previous point is a specific case of this rule: We should always be careful not to over-generalize our exception handlers. The reasons are the same; whenever we rescue more exceptions than we should, we end up hiding parts of the application logic from higher levels of the application, not to mention suppressing the developer’s ability to handle the exception his or herself. This severely affects the extensibility and maintainability of the code.
    If we do attempt to handle different exception subtypes in the same handler, we introduce fat code blocks that have too many responsibilities. For example, if we are building a library that consumes a remote API, handling a MethodNotAllowedError (HTTP 405), is usually different from handling an UnauthorizedError (HTTP 401), even though they are both ResponseErrors.
    As we will see, often there exists a different part of the application that would be better suited to handle specific exceptions in a more DRY way.
    So, define the single responsibility of your class or method, and handle the bare minimum of exceptions that satisfy this responsibility requirement. For example, if a method is responsible for getting stock info from a remote a API, then it should handle exceptions that arise from getting that info only, and leave the handling of the other errors to a different method designed specifically for these responsibilities:

    def get_info
      begin
        response = HTTP.get(STOCKS_URL + "#{@symbol}/info")
        fail AuthenticationError if response.code == 401
        fail StockNotFoundError, @symbol if response.code == 404
        return JSON.parse response.body
      rescue JSON::ParserError
        retry
      end
    end
    

    Here we defined the contract for this method to only get us the info about the stock. It handles endpoint-specific errors, such as an incomplete or malformed JSON response. It doesn’t handle the case when authentication fails or expires, or if the stock doesn’t exist. These are someone else’s responsibility, and are explicitly passed up the call stack where there should be a better place to handle these errors in a DRY way.

    Resist the urge to handle exceptions immediately

    This is the complement to the last point. An exception can be handled at any point in the call stack, and any point in the class hierarchy, so knowing exactly where to handle it can be mystifying. To solve this conundrum, many developers opt to handle any exception as soon as it arises, but investing time in thinking this through will usually result in finding a more appropriate place to handle specific exceptions.
    One common pattern that we see in Rails applications (especially those that expose JSON-only APIs) is the following controller method:

    # app/controllers/client_controller.rb
    def create
      @client = Client.new(params[:client])
      if @client.save
        render json: @client
      else
        render json: @client.errors
      end
    end
    

    (Note that although this is not technically an exception handler, functionally, it serves the same purpose, since @client.save only returns false when it encounters an exception.)
    In this case, however, repeating the same error handler in every controller action is the opposite of DRY, and damages maintainability and extensibility. Instead, we can make use of the special nature of exception propagation, and handle them only once, in the parent controller class, ApplicationController:

    # app/controllers/client_controller.rb
    def create
      @client = Client.create!(params[:client])
      render json: @client
    end
    
    # app/controller/application_controller.rb
    rescue_from ActiveRecord::RecordInvalid, with: :render_unprocessable_entity
    def render_unprocessable_entity(e)
      render \
        json: { errors: e.record.errors },
        status: 422
    end
    

    This way, we can ensure that all of the ActiveRecord::RecordInvalid errors are properly and DRY-ly handled in one place, on the base ApplicationController level. This gives us the freedom to fiddle with them if we want to handle specific cases at the lower level, or simply let them propagate gracefully.

    Not all exceptions need handling

    When developing a gem or a library, many developers will try to encapsulate the functionality and not allow any exception to propagate out of the library. But sometimes, it’s not obvious how to handle an exception until the specific application is implemented.
    Let’s take ActiveRecord as an example of the ideal solution. The library provides developers with two approaches for completeness. The save method handles exceptions without propagating them, simply returning false, while save! raises an exception when it fails. This gives developers the option of handling specific error cases differently, or simply handling any failure in a general way.
    But what if you don’t have the time or resources to provide such a complete implementation? In that case, if there is any uncertainty, it is best to expose the exception, and release it into the wild.
    Sometimes the best way to handle an exception is to let it fly free.
    Here’s why: We are working with moving requirements almost all the time, and making the decision that an exception will always be handled in a specific way might actually harm our implementation, damaging extensibility and maintainability, and potentially adding huge technical debt, especially when developing libraries.
    Take the earlier example of a stock API consumer fetching stock prices. We chose to handle the incomplete and malformed response on the spot, and we chose to retry the same request again until we got a valid response. But later, the requirements might change, such that we must fall back to saved historical stock data, instead of retrying the request.
    At this point, we will be forced to change the library itself, updating how this exception is handled, because the dependent projects won’t handle this exception. (How could they? It was never exposed to them before.) We will also have to inform the owners of projects that rely on our library. This might become a nightmare if there are many such projects, since they are likely to have been built on the assumption that this error will be handled in a specific way.
    Now, we can see where we are heading with dependencies management. The outlook is not good. This situation happens quite often, and more often than not, it degrades the library’s usefulness, extensibility, and flexibility.
    So here is the bottom line: if it is unclear how an exception should be handled, let it propagate gracefully. There are many cases where a clear place exists to handle the exception internally, but there are many other cases where exposing the exception is better. So before you opt into handling the exception, just give it a second thought. A good rule of thumb is to only insist on handling exceptions when you are interacting directly with the end-user.

    Follow the convention

    The implementation of Ruby, and, even more so, Rails, follows some naming conventions, such as distinguishing between method_names and method_names! with a “bang.” In Ruby, the bang indicates that the method will alter the object that invoked it, and in Rails, it means that the method will raise an exception if it fails to execute the expected behavior. Try to respect the same convention, especially if you are going to open-source your library.
    If we were to write a new method! with a bang in a Rails application, we must take these conventions into account. There is nothing forcing us to raise an exception when this method fails, but by deviating from the convention, this method may mislead programmers into believing they will be given the chance to handle exceptions themselves, when, in fact, they will not.
    Another Ruby convention, attributed to Jim Weirich, is to use fail to indicate method failure, and only to use raise if you are re-raising the exception.

    “An aside, because I use exceptions to indicate failures, I almost always use the “fail” keyword rather than the “raise” keyword in Ruby. Fail and raise are synonyms so there is no difference except that “fail” more clearly communicates that the method has failed. The only time I use “raise” is when I am catching an exception and re-raising it, because here I’m not failing, but explicitly and purposefully raising an exception. This is a stylistic issue I follow, but I doubt many other people do.”

    Many other language communities have adopted conventions like these around how exceptions are treated, and ignoring these conventions will damage the readability and maintainability of our code.

    Logger.log(everything)

    This practice doesn’t solely apply to exceptions, of course, but if there’s one thing that should always be logged, it’s an exception.
    Logging is extremely important (important enough for Ruby to ship a logger with its standard version). It’s the diary of our applications, and even more important than keeping a record of how our applications succeed, is logging how and when they fail.
    There is no shortage of logging libraries or log-based services and design patterns. It’s critical to keep track of our exceptions so we can review what happened and investigate if something doesn’t look right. Proper log messages can point developers directly to the cause of a problem, saving them immeasurable time.

    That Clean Code Confidence

    Proper exception handling allows for clean code and successful software.

    Clean exception handling will send your code quality to the moon!

    Exceptions are a fundamental part of every programming language. They are special and extremely powerful, and we must leverage their power to elevate the quality of our code instead of exhausting ourselves fighting with them.
    In this article, we dived into some good practices for structuring our exception trees and how it can be beneficial for readability and quality to logically structure them. We looked at different approaches for handling exceptions, either in one place or on multiple levels.
    We saw that it’s bad to “catch ‘em all”, and that it’s ok to let them float around and bubble up.
    We looked at where to handle exceptions in a DRY manner, and learned that we are not obligated to handle them when or where they first arise.
    We discussed when exactly it is a good idea to handle them, when it’s a bad idea, and why, when in doubt, it’s a good idea to let them propagate.
    Finally, we discussed other points that can help maximize the usefulness of exceptions, such as following conventions and logging everything.
    With these basic guidelines, we can feel much more comfortable and confident dealing with error cases in our code, and making our exceptions truly exceptional!
    Special thank to Avdi Grimm and his awesome talk Exceptional Ruby, which helped a lot in the making of this article.
    The author of this post is Ahmed AbdelRazzak & the originally published on Toptal.

  • Gulp: A Web Developer's Secret Weapon for Maximizing Site Speed

    Many of us have to handle web based projects that are used in production, which provide various services to the public. When dealing with such projects, it is important to be able to build and deploy our code quickly. Doing something quickly often leads to errors, especially if a process is repetitive, therefore it’s a good practice to automate such a process as much as possible.
    Gulp: A Web Developer's Secret Weapon for Maximizing Site Speed

    My fellow developers: There is no excuse for serving junk to your browser.

    In this post, we will be looking at a tool that can be a part of what will allow us to achieve such automation. This tool is an npm package called Gulp.js. In order to become familiar with the basic Gulp.js terminology used in this post, please refer to “An Introduction to JavaScript Automation with Gulp” that was previously published on the blog by Antonios Minas, one of our fellow Toptal developers. We will assume basic familiarity with the npm environment, as it is used extensively throughout this post to install packages.

    Serving Front-End Assets

    Before we continue, let’s take a few steps back to get an overview of the problem that Gulp.js can solve for us. Many web-based projects feature front-end JavaScript files that are served to the client in order to provide various functionalities to the web page. Usually there’s also a set of CSS stylesheets that are served to the client as well. Sometimes when looking at the source code of a website or a web application, we can see code like this:

    <link href="css/main.css" rel="stylesheet">
    <link href="css/custom.css" rel="stylesheet">
    <script src="js/jquery.min.js"></script>
    <script src="js/site.js"></script>
    <script src="js/module1.js"></script>
    <script src="js/module2.js"></script>
    

    There are a few problems with this code. It has references to two separate CSS stylesheets and four separate JavaScript files. This means that the server has to make a total of six requests to the server, and each request has to separately load a resource before the page will be ready. This is less of an issue with HTTP/2 because HTTP/2 introduces parallelism and header compression, but it’s still an issue. It increases the total volume of traffic that is required to load this page, and reduces the quality of user experience because it takes longer to load the files. In case of HTTP 1.1, it also hogs the network and reduces the number of request channels that are available. It would have been much better to combine the CSS and JavaScript files into a single bundle for each. That way, there would be only a total of two requests. It would also have been nice to serve minified versions of these files, which are usually much smaller than the originals. Our web application might also break if any of the assets are cached, and the client would receive an outdated version.
    Overload
    One primitive approach to solving some of these problems is to manually combine each type of asset into a bundle using a text editor, and then run the result through a minifier service, such as https://jscompress.com/. This proves to be very tedious to do continuously during the development process. A slight but questionable improvement would be to host our own minifier server, using one of the packages available on GitHub. Then we could do things that would look somewhat similar to the following:

    <script src="min/f=js/site.js,js/module1.js"></script>
    

    This would serve minified files to our client, but it would not solve the problem of caching. It would also cause additional load on the server, since our server would essentially have to concatenate and minify all the source files repetitively on every request.

    Automating with Gulp.js

    Surely we can do better than either of these two approaches. What we really want is to automate bundling and include it in the build phase of our project. We want to end up with pre-built asset bundles that are already minified and are ready to serve. We also want to force the client to receive the most up to date versions of our bundled assets on every request, but we still want to leverage caching if possible. Luckily for us, Gulp.js can handle that. In the remainder of the article, we will be building a solution that will leverage the power of Gulp.js to concatenate and minify the files. We will also be using a plugin to bust the cache when there are updates.
    We will be creating the following directory and file structure in our example:

    public/
    |- build/
       |- js/
          |- bundle-{hash}.js
       |- css/
          |- stylesheet-{hash}.css
    assets/
    |- js/
       |- vendor/
       |- jquery.js
       |- site.js
       |- module1.js
       |- module2.js
    |- css/
       |- main.css
       |- custom.css
    gulpfile.js
    package.json
    
    npm makes package management in Node.js projects a bliss. Gulp provides tremendous extensibility by taking advantage of npm’s simple packaging approach to deliver modular and powerful plugins.

    The gulpfile.js file is where we will define the tasks that Gulp will perform for us. The package.json is used by npm to define our application’s package and track the dependencies that we will be installing. The public directory is what should be configured to face the web. The assets directory is where we will store our source files. To use Gulp in the project, we will need to install it via npm, and save it as a developer dependency for the project. We will also want to start with the concat plugin for Gulp, which will allow us to concatenate multiple files into one.
    To install these two items, we will run the following command:

    npm install --save-dev gulp gulp-concat
    

    Next, we will want to begin writing the content of gulpfile.js.

    var gulp = require('gulp');
    var concat = require('gulp-concat');
    gulp.task('pack-js', function () {
    	return gulp.src(['assets/js/vendor/*.js', 'assets/js/main.js', 'assets/js/module*.js'])
    		.pipe(concat('bundle.js'))
    		.pipe(gulp.dest('public/build/js'));
    });
    gulp.task('pack-css', function () {
    	return gulp.src(['assets/css/main.css', 'assets/css/custom.css'])
    		.pipe(concat('stylesheet.css'))
    		.pipe(gulp.dest('public/build/css'));
    });
    gulp.task('default', ['pack-js', 'pack-css']);
    

    Here, we are loading the gulp library and its concat plugin. We then define three tasks.

    The first task (pack-js) defines a procedure to compress multiple JavaScript source files into one bundle. We list the source files, which will be globbed, read, and concatenated in the order specified. We pipe that into the concat plugin to get one final file called bundle.js. Finally, we tell gulp to write the file to public/build/js.
    The second task (pack-css) does the same thing as above, but for the CSS stylesheets. It tells Gulp to store the concatenated output as stylesheet.css in public/build/css.
    The third task (default) is the one Gulp runs when we invoke it with no arguments. In the second parameter, we pass the list of other tasks to execute when the default task is ran.
    Let’s paste this code into gulpfile.js using any source code editor that we normally use, and then save the file to the application root.
    Next, we will open the command line and run:

    gulp
    

    If we look at our files after running this command, we will find two new files: public/build/js/bundle.js and public/build/css/stylesheet.css. They are concatenations of our source files, which solves part of the original problem. However, they are not minified, and there is no cache busting yet. Let’s add automated minification.

    Optimizing Built Assets

    We will need two new plugins. To add them, we will run the following command:

    npm install --save-dev gulp-clean-css gulp-minify
    

    The first plugin is for minifying CSS, and the second one is for minifying JavaScript. The first one uses the clean-css package, and the second one uses the UglifyJS2 package. We will load these two packages in our gulpfile.js first:

    var minify = require('gulp-minify');
    var cleanCss = require('gulp-clean-css');
    

    We will then need to use them in our tasks just before we write the output to disk:

    .pipe(minify())
    .pipe(cleanCss())
    

    The gulpfile.js should now look like this:

    var gulp = require('gulp');
    var concat = require('gulp-concat');
    var minify = require('gulp-minify');
    var cleanCss = require('gulp-clean-css');
    gulp.task('pack-js', function () {
    	return gulp.src(['assets/js/vendor/*.js', 'assets/js/main.js', 'assets/js/module*.js'])
    		.pipe(concat('bundle.js'))
    		.pipe(minify())
    		.pipe(gulp.dest('public/build/js'));
    });
    gulp.task('pack-css', function () {
    	return gulp.src(['assets/css/main.css', 'assets/css/custom.css'])
    		.pipe(concat('stylesheet.css'))
    		.pipe(cleanCss())
       .pipe(gulp.dest('public/build/css'));
    });
    gulp.task('default', ['pack-js', 'pack-css']);
    

    Let’s run gulp again. We will see that the file stylesheet.css is saved in minified format, and the file bundle.js is still saved as is. We will notice that we now also have bundle-min.js, which is minified. We want only the minified file, and we want it saved as bundle.js, so we will modify our code with additional parameters:

    .pipe(minify({
    	ext:{
    		min:'.js'
    	},
    	noSource: true
    }))
    

    As per gulp-minify plugin documentation (https://www.npmjs.com/package/gulp-minify), this will set the desired name for the minified version, and tell the plugin not to create the version containing the original source. If we delete the content of the build directory and run gulp from the command line again, we will end up with just two minified files. We have just finished implementing the minification phase of our build process.

    Cache Busting

    Next, we will want to add cache busting, and we will need to install a plugin for that:

    npm install --save-dev gulp-rev
    

    And require it in our gulp file:

    var rev = require('gulp-rev');
    

    Using the plugin is a bit tricky. We have to pipe the minified output through the plugin first. Then, we have to call the plugin again after we write the results to disk. The plugin renames the files so that they are tagged with a unique hash, and it also creates a manifest file. The manifest file is a map that can be used by our application to determine the latest filenames that we should refer to in our HTML code. After we modify the gulp file, it should end up looking like this:

    var gulp = require('gulp');
    var concat = require('gulp-concat');
    var minify = require('gulp-minify');
    var cleanCss = require('gulp-clean-css');
    var rev = require('gulp-rev');
    gulp.task('pack-js', function () {
        return gulp.src(['assets/js/vendor/*.js', 'assets/js/main.js', 'assets/js/module*.js'])
            .pipe(concat('bundle.js'))
            .pipe(minify({
                ext:{
                    min:'.js'
                },
                noSource: true
            }))
            .pipe(rev())
            .pipe(gulp.dest('public/build/js'))
            .pipe(rev.manifest())
            .pipe(gulp.dest('public/build'));
    });
    gulp.task('pack-css', function () {
        return gulp.src(['assets/css/main.css', 'assets/css/custom.css'])
            .pipe(concat('stylesheet.css'))
            .pipe(cleanCss())
            .pipe(rev())
                .pipe(gulp.dest('public/build/css'))
            .pipe(rev.manifest())
            .pipe(gulp.dest('public/build'));
    });
    gulp.task('default', ['pack-js', 'pack-css']);
    
    With proper cache busting in place, you can go nuts with long expiry time for your JS and CSS files and reliably replace them still with newer versions whenever necessary.

    Let’s delete the contents of our build directory and run gulp again. We will find that we now have two files with hash tags affixed to each of the filenames, and a manifest.json saved to public/build. If we open the manifest file, we will see that it only has a reference to one of our minified and tagged files. What is happening is that each task writes a separate manifest file, and one of them ends up overwriting the other. We will need to modify the tasks with additional parameters that will tell them to look for the existing manifest file, and to merge the new data into it if it exists. The syntax for that is a bit complicated, so let’s look at what the code should look like and then go over it:

    var gulp = require('gulp');
    var concat = require('gulp-concat');
    var minify = require('gulp-minify');
    var cleanCss = require('gulp-clean-css');
    var rev = require('gulp-rev');
    gulp.task('pack-js', function () {
        return gulp.src(['assets/js/vendor/*.js', 'assets/js/main.js', 'assets/js/module*.js'])
            .pipe(concat('bundle.js'))
            .pipe(minify({
                ext:{
                    min:'.js'
                },
                noSource: true
            }))
            .pipe(rev())
            .pipe(gulp.dest('public/build/js'))
            .pipe(rev.manifest('public/build/rev-manifest.json', {
                merge: true
            }))
            .pipe(gulp.dest(''));
        });
    gulp.task('pack-css', function () {
        return gulp.src(['assets/css/main.css', 'assets/css/custom.css'])
            .pipe(concat('stylesheet.css'))
            .pipe(cleanCss())
            .pipe(rev())
            .pipe(gulp.dest('public/build/css'))
            .pipe(rev.manifest('public/build/rev-manifest.json', {
                merge: true
            }))
            .pipe(gulp.dest(''));
    });
    gulp.task('default', ['pack-js', 'pack-css']);
    

    We are piping the output to rev.manifest() first. This creates tagged files instead of the files that we had before. We are providing the desired path of our rev-manifest.json, and telling rev.manifest() to merge into the existing file, if it exists. Then we are telling gulp to write the manifest to the current directory, which at that point will be public/build. The path issue is due to a bug that is discussed in more detail on GitHub.
    We now have automated minification, tagged files, and a manifest file. All of this will allow us to deliver the files more quickly to the user, and bust their cache whenever we make our modifications. There are just two remaining problems though.
    The first problem is that if we make any modifications to our source files, we will get new tagged files, but the old ones will remain there as well. We need some way to automatically delete old minified files. Let’s solve this problem using a plugin that will allow us to delete files:

    npm install --save-dev del
    

    We will require it in our code and define two new tasks, one for each type of source file:

    var del = require('del');
    gulp.task('clean-js', function () {
    	return del([
    		'public/build/js/*.js'
    	]);
    });
    gulp.task('clean-css', function () {
    	return del([
    		'public/build/css/*.css'
    	]);
    });
    

    We will then make sure that the new task finishes running before our two main tasks:

    gulp.task('pack-js', ['clean-js'], function () {
    gulp.task('pack-css', ['clean-css'], function () {
    

    If we run gulp again after this modification, we will have just the latest minified files.
    The second problem is that we don’t want to keep running gulp every time we make a change. To solve this, we will need to define a watcher task:

    gulp.task('watch', function() {
     gulp.watch('assets/js/**/*.js', ['pack-js']);
     gulp.watch('assets/css/**/*.css', ['pack-css']);
    });
    

    We will also change the definition of our default task:

    gulp.task('default', ['watch']);
    

    If we now run gulp from the command line, we will find that it no longer builds anything upon invocation. This is because it now calls the watcher task that will watch our source files for any changes, and build only when it detects a change. If we try changing any of our source files, and then look at our console again, we will see that the pack-js and pack-css tasks run automatically along with their dependencies.
    Now, all we have to do is load the manifest.json file in our application and get the tagged filenames from that. How we do that depends on our particular back-end language and technology stack, and would be quite trivial to implement, so we will not go over it in detail. However, the general idea, is that we can load the manifest into an array or an object, and then define a helper function that will allow us to call versioned assets from our templates in a manner similar to the following:

    gulp(‘bundle.js’)
    

    Once we do that, we will not have to worry about changed tags in our filenames ever again, and we will be able to focus on writing high quality code.
    The final source code for this article, along with a few sample assets, can be found in this GitHub repository.

    Conclusion

    In this article, we went over how to implement Gulp based automation for our build process. I hope that this proves helpful to you and allows you to develop more sophisticated build processes in your own applications.
    Please keep in mind that Gulp is just one of the tools that can be used for this purpose, and there are many others such as Grunt, Browserify, and Webpack. They vary in their purposes and in the scope of problems that they can solve. Some can solve problems that Gulp cannot, such as bundling JavaScript modules with dependencies that can be loaded on demand. This is referred to as “code splitting”, and it is an improvement over the idea of serving one big file with all parts of our program on every page. These tools are quite sophisticated, but might be covered in the future. In a following post, we will go over how to automate the deployment of our application.
    This post was originally published on Toptal Engineering blog

  • Auto Screen Rotate/G-Sensor Issue in Windows 10 Tablet

    Auto Screen Rotate/G-Sensor Issue in Windows 10 Tablet

    So you just update your windows tablet from Windows 8/8.1 to windows 10. And you didn’t find Auto Screen Rotate option in Windows 10.

    The same issue I was facing from once I update Windows 10. first I thought Windows 10 doesn’t support Auto Rotate Screen. So, I use it around 4 month. But one day I found a Video of Unboxing windows tablet and it has the Auto Screen Rotate feature. So I start finding solution for my tablet “iBall Slide WQ32”. I tried many drivers but some drivers work and some not. and the working drivers work weird It work like I hold tablet horizontal but screen rotate to vertical. I was completely shocked by its behavior. So I start my R&D in registry and the final solution I found is described here.

    Follow this steps but let me clear one thing I AM NOT RESPONSIBLE FOR ANY KIND OF SYSTEM DAMAGE.

    1. Download KIONIXdriver from this URL: https://www.kionix.com/downloads

      (select KXTJ9-KXCJ9-KXTJ2 Driver for Windows 7/8/10)

    2. Extract it and install. if you are on 64bit then install x64 driver else x86.
    3. Restart your tablet.
    4. Now go to Setting > System > Display > you will see a new option there “Lock Auto Rotate Screen” so turn it off.

    Now you have 3 conditions there

    1. Your screen rotation will work fine on all Degree.
    2. Your screen will rotate upside down
    3. Your screen will rotate 1 Step next. E.g. You hold your tablet at Horizontal but it rotate vertical.

    To prevent this issue you have to got Registry.

    How to go to Registry?

    Tap and hold on Start icon at bottom left you will see menu. In that menu you will see option “Run” tap on that.

    A box will appear now type on that box “regedit”. Hit enter or tap on OK.

    Now a register editor will open. Now go to

    HKEY_LOCAL_MACHINE > SYSTEM > CurrentControlSet > Enum > ROOT > SENSOR > 0000 > Device Parameters > kxfusion

    So the path will be :

    HKEY_LOCAL_MACHINESYSTEMCurrentControlSetEnumROOTSENSOR000Device Parameterskxfusion
    

    if you are tech geek and know about HEX value then hit and try Orientation value

    00,00,00,00,01,01,02
    01,01,00,00,00,00,02
    00,01,00,01,00,01,02
    01,00,01,00,01,00,02

    Or just download my registry from:

    [wpdm_package id=’2550′]

    But always remember after modifying anything in registry you have to RESTART your system.

    in my zip there is already driver attached. but if you want to download latest version then please go to https://www.kionix.com/downloads.

    About my Tablet:

    iBall Slide WQ32

    • 16 GB internal
    • 2 GB Ram
    • Wi-Fi + 3G (Without Calling Facility)
    • 8 inch Screen
    • Screen Resolution 1280 x 800 pixels
    • 8 cm (18) Screen Size
    • IPS Screen
    • 2 Megapixel front camera
    • 5 Megapixel primary camera
    • 83 GHz Intel Atom Processor Z3735D
    • Storage expand upto 64 GB

    Also you can connect external Hard Drive, Keyboard Mouse and all other peripherals which supported by windows 10.

    You can purchase it from This link.

  • Send email in Cakephp using SMTP With Source and Video

    Send email in Cakephp using SMTP With Source and Video

    How to send mail in CakePHP 2.x
    First you have to configure your cakephp for sending mail.
    Go to:

    App/Config/email.php

    Now there are two method you can use:

    1. Using sendmail function
    2. Using SMTP

    For sendmail :

    public $default = array(
    		'transport' => 'Mail',
    		'from' => '[email protected]',
    		'charset' => 'utf-8',
    		'headerCharset' => 'utf-8',
    	);
    

    For SMTP:

    public $smtp = array(
    		'transport' => 'Smtp',
    		'from' => array([email protected]' => Sender name),
    		'host' => 'ssl://smtp.gmail.com',
    		'port' => 465,
    		'timeout' => 30,
    		'username' => [email protected]',
    		'password' => PASSWORD,
    		'client' => null,
    		'log' => false,
    		'charset' => 'utf-8',
    		'headerCharset' => 'utf-8',
    	);
    

    Now you have setup you mail config file.
    Now we will send mail:

    $Email = new CakeEmail('smtp'); // Replace Smtp to default if you don’t want send mail from SMTP
            $Email->to('[email protected]');
            $Email->emailFormat('html');
            $Email->template('default')->viewVars( array('body'=>"Hi this is a mail from cakePHP"));
    // pass your variables here.
            $Email->subject('My First Mail from cakephp');
            $Email->from ('[email protected]');
            $Email->send();
    

    To edit or customize your mail template you have to edit/create your email template file:

    app/View/Emails/html/default.ctp
    <html>
    <h1>Hi</h1>
    <p><?php echo $body; ?></p>
    </html>
    

     

    [wpdm_package id=’2544′]

    for more information you can check CakePHP documentation.