678 snippets – displaying 1–30

How to get notified when a Cron job fails

To get notified when a cron script fails you can tell cron to send any errors to you by email.

It already does this by default, but the emails are sent to the Unix account’s mailbox:

cat /var/spool/mail/<username> | less

To use a different email address use the MAILTO setting as described here:

MAILTO=email@example.com
0 */2 * * * /bin/backup.sh > /dev/null

Cron will now send an email whenever the script (/bin/backup.sh) prints something to stderr.

If the script is printing to stderr without it failing try Cronic:

0 */2 * * * cronic /bin/backup.sh

You can of course also try to fix the script by not printing to STDERR unless it’s really an error.

Check the mail log to see if it’s working:

sudo tail -f /var/log/mail.log

If you’re email server is rejecting emails sent by cron you might need to set the MAILFROM variable. However, only some cron version supports MAILFROM.

How to mark deprecated methods in Ruby

This code can be used to mark deprecated methods in Ruby:

module Kernel
  def mark_deprecated(new_method)
    warn "DEPRECATED: the #{__method__} called from #{caller.first} has been deprecated and replaced by #{new_method}!!!"
  end
end

Example:

class Horse
  def self.shit
    mark_deprecated("Bull.shit")
  end
end

Checklist for how to write Sidekiq jobs

  1. Use a reconsiliation step to make sure jobs are executed correctly, e.g. at least once: http://www.mikeperham.com/2014/05/27/the-reconciliation-step/
  2. Jobs should be idempotent, i.e. even if a job is performed multiple times the work should only be performed once.
  3. When needed, use locking strategies to prevent code from being executed in parallel. For example, use a global filesystem or database lock when writing to disk, or when updating and inserting data into the database use optimistic/pessimistic locking, or foreign key constraints.
  4. Set retry to zero for jobs that don’t need to or shouldn’t be retried.
  5. Specify a queue and a queue priority for jobs that need a higher or lower priority.
  6. Does the job need database transactions? Use transactions e.g. when a job does more than one insert, update, delete, or create, otherwise you will end up having data duplication/inconsistency issues.

Using Ruby 2.2.0 with Rails 3.x

rubyrailschristianVersion 4

Steps for upgrading a Rails 3.x app to Ruby 2.2.0:

  1. Install Ruby 2.2.0, e.g. brew update; brew upgrade ruby-build; rbenv install 2.2.0
  2. Set app’s ruby version to 2.2.0, e.g. rbenv local 2.2.0
  3. Update gems that are broken, e.g. bundle update pg eventmachine rubocop
  4. Add test-unit to Gemfile to fix “cannot load such file — test/unit/testcase (LoadError)” error:

gem 'test-unit'

  1. Rollback to 2.1 when you notice all warnings, related to e.g. Comparable, or continue with the warnings

JavaScript Promises With Q.js

This Q.js example calls two asynchronous methods in sequence:

class InitializeApp
  constructor: ->
    findDevice = ->
      df = Q.defer()
      onSuccess = (devices) ->
        console.log "Finding device"
        df.resolve("device 2")
      setTimeout(onSuccess, 2000)
      df.promise

    connectToDevice = (id) ->
      df = Q.defer()
      onSuccess = ->
        console.log "Connecting to #{id}"
        df.resolve("success")
      setTimeout(onSuccess, 2000)
      df.promise

    findDevice().then(connectToDevice)

Usage:

new InitializeApp()
# ...Sleep 2 seconds
# => Finding device
# ...Sleep 2 seconds
# => Connecting to device 2

How to use Font Awesome in iOS/Phonegap apps

First, install Font Awesome:

  1. Download the latest Font Awesome version
  2. Double-click fontawesome-webfont.ttf and install it on your laptop/desktop (optional)
  3. Copy fontawesome.css to www/css
  4. Remove the references to font files in fontawesome.css, i.e. remove @font-face declaration

Then in Xcode:

  1. Copy fontawesome-webfont.ttf into “Your Project/Resources/fonts/fontawesome-webfont.ttf”
  2. Add Font Awesome to the .plist file by selecting the “Info” tab
  3. Add a new property named “Fonts provided by application” and set the value to “fontawesome-webfont.ttf”

Clean and build your project. Font Awesome is now ready to be used.

Phonegap example:

<i class="fa fa-cog"/>

How to hide the status bar in a Phonegap iOS app

To hide the status bar in a phonegap project:

  1. Double click on your project, or .plist, in XCode
  2. Select the tab named “Info”
  3. Add a new property by selecting an item in the list and then clicking the plus sign
  4. Name the property “View controller-based status bar appearance”
  5. Set the property value to “NO”

Next:

  1. Select the tab named general
  2. Check the “Hide status bar” located under “Deployment Info”

Done.

How to Open Safari's Web Inspector With Applescript to Debug a Phonegap App

This applescript will make Safari’s Web Inspector connect to a Phonegap application running on my iPhone that was started through XCode:

#!/usr/bin/osascript

set device_name to "Christian Hellsten iPhone"
tell application "Safari"
	activate
	tell application "System Events"
		try
			click menu item "index.html" of menu device_name of menu item device_name of menu "Utvecklare" of menu bar item "Utvecklare" of menu bar 1 of application process "Safari"
		end try
	end tell
end tell

Save the file, as e.g. open-web-inspector.applescript, then execute it:

chmod +x open-web-inspector.applescript
./open-web-inspector.applescript

For English version, change “Utvecklare” to “Develop”.

Troubleshooting

  1. Error -1719 most likely means you need to enable assistive access for iTerm or whatever app you’re running the script from.
  1. Error -10810 means “bad luck” in Applescript. Try restarting the computer.

If all else fails, run the script using the Applescript Editor. Also see, this script.

Tested on OSX Yosemite.

CoffeeScript variable visibility

coffeescriptchristianVersion 3

This Coffeescript:

class Device
  x: 1 # Instance variable
  y = 2 # Private instance variable
  @z: 3 # Class variable

 # Address and name are instance variables
  constructor: (@address, @name) ->

gives us this JavaScript:

Device = (function() {
  var y;
  Device.prototype.x = 1;
  y = 2;
  function Device(address, name) {
    this.address = address;
    this.name = name;
  }
  return Device;
})();

and the following visibility:

dev = new Device('X', 'Y') # => Device {address: "X", name: "Y", x: 1}
dev.y # => undefined
Device.z # => 3

How to Debug Phonegap Applications With Safari's Remote Debugger

  1. On your iPhone/iPad: Enable Web Inspector . Open “Settings” → “Safari” → “Advanced”.
  2. On your desktop/laptop: Enable Developer tools in Safari. Open “Preferences” → “Advanced” check “Show Develop menu in menu bar”.
  3. Connect your iPhone via USB to your desktop/laptop.
  4. Start the application on your iPad/iPhone via XCode.
  5. On your desktop/laptop: Open the Safari Web Inspect debugger. Go to “Preferences” → “Your phone” → “index.html”.

You can automate the last step by using applescript to open Safari’s Web Inspector.

Note: Use CMD+R to reload index.html.

Phonegap Autorotate

In MainViewController#shouldAutorotateToInterfaceOrientation return YES:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES; //[super shouldAutorotateToInterfaceOrientation:interfaceOrientation];
}

Running a Phonegap App in a Specific Version of iPhone

Cordova:

cordova emulate ios --target="iPhone-4s"
cordova emulate ios --target="iPad-Air"
cordova emulate ios --target="iPhone-6"
cordova emulate ios --target="iPhone-6-Plus"

Phonegap:

phonegap run ios --target="iPhone-4s"
phonegap run ios --target="iPad-Air"
phonegap run ios --target="iPhone-6"
phonegap run ios --target="iPhone-6-Plus"

Gulpfile.js example with Slim, Coffeescript, Sass, Browser Sync, Lint

slimgulpchristianVersion 7

A Gulpfile.js example with Slim, Coffeescript, Sass, Browser Sync, Lint. The script is suitable for building e.g. static websites and prototyping mobile apps.

Gulpfile expects your project to be structured in the following way (configurable):
- src/css/.scss,.css
- src/js/.coffee,.js
- src/*.slim

Output is written to “www” folder.

#
# Gulpfile with:
#
# - Slim
# - Sass
# - Lint
# - Browsersync
# - CSS and HTML compression
#
# Install dependencies:
#
#   $ npm install gulp gulp-concat gulp-uglify event-stream gulp-coffee gulp-sass gulp-cssmin gulp-coffee gulp-coffeelint browser-sync gulp-util gulp-shell
#
# Then start developing:
#
#   $ gulp
#

gulp        = require 'gulp'
concat      = require 'gulp-concat'
es          = require('event-stream')
sass        = require 'gulp-sass'
uglify      = require 'gulp-uglify'
streamqueue = require 'streamqueue' # Preserves file order (vendor...)
coffee      = require 'gulp-coffee'
gutil       = require 'gulp-util'
shell       = require 'gulp-shell'
cssmin      = require 'gulp-cssmin'
coffeelint  = require 'gulp-coffeelint'
browserSync = require 'browser-sync'

isProd = gutil.env.type is 'prod'

sources =
  sass: 'src/css/**/*.scss'
  css: 'src/css/**/*.css'
  html: 'src/**/*.slim'
  js: 'src/js/**/*.js'
  coffee: 'src/js/**/*.coffee'

targets =
  css: 'www/css'
  html: 'www/'
  js: 'www/js'

# Check for errors
gulp.task 'lint', ->
  gulp.src(sources.js)
    .pipe(coffeelint())
    .pipe(coffeelint.reporter())

# Compile Coffeescript
gulp.task 'js', ->
  stream = streamqueue(objectMode: true)
  # Vendor files
  stream.queue(gulp.src(sources.js))
  # App files use Coffee
  stream.queue(gulp.src(sources.coffee).pipe(coffee(bare:true)))
  stream.done()
    .pipe(concat("all.js"))
    .pipe(if isProd then uglify() else gutil.noop())
    .pipe(gulp.dest(targets.js))

# Compile Slim
gulp.task 'slim', ->
  gulp.src(sources.html)
    .pipe(shell(["slimrb -r ./lib/helpers.rb -p <%= file.path %> > ./#{targets.html}/<%= file.relative.replace(\".slim\", \".html\") %>"]))

# Compile CSS
gulp.task 'css', ->
  stream = streamqueue(objectMode: true)
  # Vendor files
  stream.queue(gulp.src(sources.css))
  # App files
  stream.queue(gulp.src(sources.sass).pipe(sass(style: 'expanded', includePaths: ['src/css'], errLogToConsole: true)))
  stream.done()
    .pipe(concat("all.css"))
    .pipe(if isProd then uglify() else gutil.noop())
    .pipe(gulp.dest(targets.css))

# Reload browser
gulp.task 'server', ->
  browserSync.init null,
    open: true
    server:
      baseDir: targets.html
    reloadDelay: 2000 # Prevent white screen of death
    watchOptions:
      debounceDelay: 1000

# Watch files for changes
gulp.task 'watch', ->
  gulp.watch sources.js, ['js']
  gulp.watch sources.css, ['css']
  gulp.watch sources.html, ['slim']
  gulp.watch 'www/**/**', (file) ->
    browserSync.reload(file.path) if file.type is "changed"

# Build everything
gulp.task 'build', ['lint', 'js', 'css', 'slim']

# Start a server and watch for file changes
gulp.task 'default', ['watch', 'server']

Writing a DSL in Ruby

rubydslchristianVersion 5

When defining a simple DSL instance_eval is your friend:

class Worker
  attr_reader :where
  def call(where, &block)
    @where = where
    instance_eval &block
  end

  def cut_trees
    puts "Cutting trees"
  end

  def make_planks
    puts "Making planks"
  end

  def i(what, &block)
    instance_eval &block
  end
end

def work where, &block
  puts "Working #{where}"
  Worker.new.(where, &block)
  puts "Going home"
end

Use the DSL like this:

work "in the woods" do
  cut_trees
  make_planks
  i "take a coffee break" do
    puts "Cooking coffee #{where}"
  end
end

Output is:

Working in the woods
Cutting trees
Making planks
Cooking coffee in the woods
Going home

Ruby's call method

rubycallchristianVersion 4

What does this print:

class RubyCall
  def call(*args)
    puts "Call: #{args}"
  end
end

xxx = RubyCall.new
xxx.("hello", 1, 2, 3)

It calls the #call method and prints “Call: [”hello", 1, 2, 3]".

If you want you can do this:

xxx::call('adsf')
xxx.call('adsf')

How to record and replay TCP traffic

tcpreplaychristianVersion 2

First attempt

1) Record TCP traffic with tcpdump to pcap file

Record traffic on ethic from host 196.0.0.1 and port 2332, write to app-traffic.pcap:

tcpdump -vvv -i eth0 host 192.168.0.1 and port 2332 -w app-traffic.pcap &

2) View captured traffic

tcpdump -qns 0 -X -r app-traffic.pcap

Edit captured traffic if needed with Wireshark.

3) Edit source IP so that it’s on your own network

See the ”example in tcprewrite documentation”:http://tcpreplay.synfin.net/wiki/tcprewrite for details on how to rewrite source IP:

$ tcprewrite --pnat=10.0.0.0/8:172.16.0.0/12,192.168.0.0/16:172.16.0.0/12 --infile=input.pcap --outfile=output.pcap --skipbroadcast

4) Replay traffic with tcplivereplay from recorded pcap file (note step #3)

”See tcpliveplay documentation”:http://tcpreplay.synfin.net/wiki/tcpliveplay for details.

Note that tcpliveplay is only available on Linux not OSX.

Second attempt

Record:

sudo tcpdump -i en0 host 192.168.0.1 and port 2332 -w app-traffic.pcap


View:

tcpdump -s 0 -n -e -x -vvv -r app-traffic.pcap

Replay:

sudo tcpreplay -i en0 -t -K app-traffic.pcap

Or use tcplivereplay (Note: Linux only):
http://tcpreplay.synfin.net/wiki/tcpliveplay#tcpliveplay

Result

I couldn’t get it to work….

Big Search Field & Button = Beautiful?

<html>
<head>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.css"/>
<style>

.search-form {
  width: 40%;
  min-width: 400px;
  border: 6px solid rgba(0, 0, 0, 0.7);
  margin: 20px auto 0;
}

input.text {
  float: left;
  width: 80%;
  border: 5px solid #fff;
  margin: 0;
  outline: none;
  font-size: 17px;
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  -ms-border-radius: 0;
  -o-border-radius: 0;
  border-radius: 0;
  -webkit-appearance: none;
  color: #3c3c3c;
}


input.text, input.button {
  padding: 15px;
  font-size: 17px;
  font-weight: 800;
  display: inline-block;
  -webkit-transition: all 0.3s ease;
  -moz-transition: all 0.3s ease;
  -o-transition: all 0.3s ease;
  transition: all 0.3s ease;
}

input.button {
  float: right;
  width: 20%;
  margin: 0;
  border: 5px solid grey;
  color: #fff;
  background-color: grey;
  -webkit-appearance: none;
  padding-left: 0;
  padding-right: 0;
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  -ms-border-radius: 0;
  -o-border-radius: 0;
  border-radius: 0;
}

.clearfix {
  overflow: auto;
}

* {
  font-family: "Helvetica", sans-serif;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

</style>
</head>
<body>
  <div class="search-form clearfix">
    <input name="query" class="text" type="text" placeholder="Find your dog&hellip;">
    <input type="submit" value="Search" class="button">
  </div>
</body>
</html>

Eventmachine Echo Server Example

require 'rubygems'
require 'eventmachine'
require 'logger'

#
# Each connection creates a new EchoServer.
#
module EchoServer
  LOG = Logger.new('echo.log')

  #
  # Called by the event loop immediately after the network connection has been
  # established, and before resumption of the network loop.
  #
  def post_init
    LOG.info "-- Connection established #{remote_ip} --"
  end

  #
  # Called by the event loop whenever data has been received by the network
  # connection. It is never called by user code.
  #
  def receive_data data
    message = "#{remote_ip}: #{data}"
    LOG.info message
    send_data message
    close_connection if data =~ /quit/i
  end

  #
  # Called by the framework whenever a connection (either a server or client
  # connection) is closed.
  #
  def unbind
    LOG.info "-- Connection closed #{remote_ip} --"
  end

  #
  # Return the IP and port of the remote client.
  #
  def remote_ip
    @remote_ip ||= begin
                     port, ip = Socket.unpack_sockaddr_in(get_peername)
                     "#{ip}:#{port}"
                   end
  end
end

EventMachine::run do
  Signal.trap("INT")  { EventMachine.stop }
  Signal.trap("TERM") { EventMachine.stop }
  EventMachine::start_server "0.0.0.0", 8080, EchoServer
end

Use telnet to test it:

$ telnet localhost 8080

Daemonization Best-Practices

Don’t daemonize your daemons

<quote>

What’s the result? In development mode, your process will run in the foreground, as yourself and log to stdout: perfect for developers. In production mode, the init system will run your process as a configured user with logging sent to a specific location and log rotated automatically. Less system administration, easier debugging, simpler code, all because you leveraged the init system to do the work for you!</quote>

Running processes

<quote>

Note: In every case, it’s assumed that you have a program that wants to run that does not daemonize on its own. Self-daemonizing programs start you down the path to hell. You can’t use any sane keepalive techniques so you have to resort to polling process lists or checking the pid or something. Even managing that pidfile gets hard when you combine it with things that change their own uid for safety (because you should never run anything as root).</quote>

Ubuntu, upstart, and creating a pid for monitoring

<quote>

If start-stop-daemon is available on your machine, I would highly recommend using it to launch your process. start-stop-daemon will handle launching the process as an unprivileged user without forking from sudo or su (recommended in the upstart cookbook) AND it also has built in support for pid file management.</quote>

Foreman

<quote>

Foreman is a manager for Procfile-based applications. Its aim is to abstract away the details of the Procfile format, and allow you to either run your application directly or export it to some other process management format.</quote>

How to introduce Rubocop in your project

Installation

Edit Gemfile:

group :development do
  gem 'rubocop' # Style guide checker
  gem 'guard-rubocop' # Rubocop plugin for Guard
end

Install:

$ bundle

Usage

Run Rubocop:

$ rubocop --auto-gen-config

Tweaking

Edit .rubocop.yml:

inherit_from: .rubocop_todo.yml

Introduce new rules gradually in priority order by enabling and moving rules from .rubocop_todo.yml to .rubocop.yml.

You can also use the Ruby style-guide’s rubocop configuration:
https://github.com/bbatsov/rubocop/blob/master/config/default.yml

Workflow integration

Run:

$ guard init rubocop

Edit Guardfile:

guard :rubocop, all_on_start: false, cli: ['--format', 'clang', '--rails'] do
  watch(%r{.+\.rb$})
  watch(%r{(?:.+/)?\.rubocop\.yml$}) { |m| File.dirname(m[0]) }
end

Editor Integration

Optionally, integrate Rubocop with your editor:

CI integration

See How to introduce rubocop and integrate into Jenkins.

How to parse a cronline/crontab/cron with Ruby

You can use the rufus-scheduler gem to parse cronline/crontab/cron with Ruby.

Gemfile:

gem 'rufus-scheduler'

Example:

require 'rufus/scheduler/cronline'
cron = Rufus::Scheduler::CronLine.new("00 00 1 * *") # 00:00 every first day of the month
#
next_time = cron.next_time(Time.current)
previous_time = cron.previous_time(Time.current)

rufus-scheduler’s cronline implementation:
https://github.com/jmettraux/rufus-scheduler/blob/master/lib/rufus/scheduler/cronline.rb

See tests for details and syntax:
https://github.com/jmettraux/rufus-scheduler/blob/master/spec/cronline_spec.rb

Cron configuration examples.

Playing with Ruby and Rails Time and Time Zones

Checklist

What you need to know to handle date and time correctly in Ruby and Rails is, at least:

  • the input’s time zone when parsing time and date.
  • the user’s time zone when calculating time and date in his/her time zone.
  • Ruby and Rails date and time handling. Use Time.current and Time.zone (Rails) to avoid using the computer’s time zone (Ruby).

Things to remember

  • Is the given time in the user’s time zone (Time.zone.local) or in UTC (Time.zone.utc)?
  • The correct time zone is needed when you’re accessing date components like e.g. year, month, day, hour, start of day, start of month, etc
  • Rails takes care of time and date handling inside the application. It’s when you accept input or want to output data that you need to tread carefully.
  • Cache carefully. Maybe you need to display date and time using JavaScripts.
  • Daylight savings, plus some countries or states don’t even have DST, but might have had 100 years ago…
  • The difference between e.g. Time.now and Time.current.
  • Possible timezones: application, user, server, and database timezone
  • APIs should output ISO-8601

require 'tzinfo'
tokyo = TZInfo::Timezone.get('Asia/Tokyo')

#
# When it's 12:00 in Tokyo, what hour is it in UTC?
#
time = tokyo.local_to_utc Time.local(2014, 01, 01, 12, 00) # => 2014-01-01 03:00:00 UTC
utc_hour = time.hour # => 3
utc_time = time.utc # => 2014-01-01 03:00:00 UTC

#
# When it's 12:00 in UTC, what hour is it in Tokyo?
#
time = tokyo.utc_to_local Time.local(2014, 01, 01, 12, 00) # => 2014-01-01 21:00:00 UTC
tokyo_hour = time.hour # => 21
tokyo_time = tokyo.local_to_utc(time) # => 2014-01-01 12:00:00 UTC

#
# Convert Tokyo time to local time, i.e. convert user's local time to our local time
#
tokyo.now # => Tue, 18 Nov 2014 03:02:28 JST +09:00
tokyo.now.utc # => 2014-11-17 18:04:20 UTC
# local_to_utc => -0900
tokyo.local_to_utc tokyo.now # => 2014-11-17 18:03:02 UTC
# utc_to_local => +0900
tokyo.utc_to_local tokyo.now # => 2014-11-18 12:03:17 UTC
Time.parse Time.find_zone!('Tokyo').now.to_s

#
# Parse input from Helsinki and input from Stockholm when input contains no time zone information
#
a = Time.find_zone!('Helsinki').parse('201411121415')
b = Time.find_zone!('Stockholm').parse('201411121315')
a == b

a = Time.use_zone 'Helsinki' do
  Time.parse('201411121415')
end
b = Time.use_zone 'Stockholm' do
  Time.zone.parse('201411121315')
end
a == b # OK

#
# Using the tzinfo library directly
#
TZInfo::Timezone.all_country_zones
zone = TZInfo::Timezone.get('Africa/Harare')

#
# Rails time zones
#
ActiveSupport::TimeZone.zones_map.values.map(&:name).sort

#
# Daylight savings, anyone?
#
tokyo = TZInfo::Timezone.get('Asia/Tokyo')
tokyo.current_period.utc_offset # Doesn't include DST
tokyo.current_period.utc_total_offset # Includes DST

Time.use_zone 'Helsinki' do
  Time.local(2014, 10, 26).dst? # => true
  Time.local(2014, 10, 27).dst? # => false
end

Time.use_zone 'Pacific Time (US & Canada)' do
  # 00:00 01.06.2014 in Los Angeles, during DST
  now = Time.zone.local(2014, 6, 1)
  puts now.dst? # => true
  offset = now.utc_offset
  puts offset / 1.hour # => -7
  # 00:00 01.12.2014 in Los Angeles, after DST
  now = Time.zone.local(2014, 12, 1)
  puts now.dst? # => false
  offset = now.utc_offset
  puts offset / 1.hour # => -8
end

#
# Beginning of day in other time zone
#
Time.use_zone 'Hawaii' do
  now = Time.local(2014, 10, 27)
  puts now.beginning_of_day.dst? # false, Hawaii doesn't follow DST although the rest of the U.S.A. does.
  puts now.beginning_of_day.utc # => 2014-10-26 22:00:00 UTC
  puts now.beginning_of_day # => 2014-10-27 00:00:00 +0200
end

#
# Misc stuff
#

Time.now.formatted_offset # => "+02:00"

def without_timezone
  times = [
    Time.now,
    Time.zone.now,
    Time.current,
    Time.now.utc
  ]

  times.each do |time|
    puts times[0].to_i == time.to_i # All OK
  end
end

def with_timezone
  times = nil
  Time.use_zone('Tokyo') do
    times = [
      Time.now,
      Time.zone.now,
      Time.current,
      Time.now.utc
    ]
  end
  Time.use_zone('Stockholm') do
    times.each do |time|
      puts times[0].to_i == time.to_i # All OK
    end
  end
end

def parse_time
  times = nil
  time = '201411121415'
  Time.use_zone('Tokyo') do
    times = [
      Time.parse(time),
      Time.parse(time).in_time_zone,
      Time.zone.parse(time).in_time_zone, # ERROR: 7 hour time difference
      Time.zone.parse(time) # ERROR: 7 hour time difference
    ]
  end
  Time.use_zone('Stockholm') do
    times.each do |time|
      binding.pry unless times[0].to_i == time.to_i
    end
  end
end

without_timezone
with_timezone
parse_time

Also see Working with time zones in Ruby on Rails.

How to run only one specific test with Rspec

Focusing on one or more tests with Rspec

You can tell Rspec to run only tests tagged with “focus: true” by running Rspec with the —tag focus switch:

rspec ./spec/controllers/concerns/session_expiry_spec.rb --tag focus

This would run e.g. only this test which is marked with “focus: true”:

it "resets session if session has expired", focus: true do
...
end

Integrating with Guard

Use this configuration to integrate this workflow with Guard:

guard 'rspec', cli: '--tag focus --format d --color', all_after_pass: false, all_on_start: false do
...
end

We also want to run all tests when there are no focused tests. We therefore add this to spec/spec_helper.rb:

RSpec.configure do |config|
  # This is dangerous with CI integration e.g. Jenkins
  # config.filter_run focus: true
  config.run_all_when_everything_filtered = true
end

Rspec configuration file

One alternative is to enable the focus option in the Rspec configuration file:

RSpec.configure do |config|
  config.filter_run :focus => true
  config.run_all_when_everything_filtered = true

However, this would be dangerous when running tests with e.g. Jenkins and when someone forgets to remove “focus: true”.