Skip to content

Instantly share code, notes, and snippets.

@ascendbruce
ascendbruce / gist:7009252
Created October 16, 2013 15:10
Ruby File open read/write examples
File.open("/usr/local/widgets/data").each do |line|
    puts line if line =~ /blue/
end



logfile = File.new("/tmp/log", "w")

logfile.close
@ascendbruce
ascendbruce / gist:7070842
Created October 20, 2013 15:08
Markdown table example

source

|name|score|
|:---|----:|
|john|   96|
|wang|   88|

output

name score
@ascendbruce
ascendbruce / gist:7070884
Created October 20, 2013 15:11
Ruby throw catch example
error = catch(:error) do
throw :error, "params uuid required" if uuid.blank?
throw :error, "params lang required" unless params.include?("lang")
end
@ascendbruce
ascendbruce / gist:7070911
Created October 20, 2013 15:13
Ruby get current file full path (absolute path)
File.expand_path(File.dirname(__FILE__))
# If you want to require some files in different directory, in ruby 1.9, you may want to use:
require_relative "../xxxlib"
@ascendbruce
ascendbruce / gist:7070932
Last active December 26, 2015 01:19
Ruby performance/benchmark measure methods
# Ruby build-in
require 'benchmark'
puts Benchmark.measure { "a"*1_000_000 } # and Benchmark.bm, Benchmark.bmbm
# handcrafted
def performance
t1 = Time.now.to_f
yield
t2 = Time.now.to_f
return t2 - t1
@ascendbruce
ascendbruce / ruby-how-to-check-string-valid-json-object.md
Last active December 22, 2023 06:39
Ruby test if a string is an valid json object

Background

I posted this gist a few years ago as a quick memo for myself. I never expect this little gist to rank up in top 3 search result and getting so many helpful feedbacks. Since it gets viewed quite often, I decided to revise this post so that it may be a little more helpful. Thank you again for the feedback!

The new answer

require "json"

class MyJSON
@ascendbruce
ascendbruce / gist:7071030
Created October 20, 2013 15:23
Meta tags and open graph og:tags examples
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta content="" name="description">
<meta content="" name="keywords">
<meta content="" property="og:image">
<meta content="" property="og:url">
<meta content="" property="og:site_name">
<meta content="" property="og:title">
<meta content="" property="og:type">
@ascendbruce
ascendbruce / gist:7071040
Created October 20, 2013 15:24
Ruby and ActiveRecord Timezone = Taipei setting
config.time_zone = 'Taipei' # For ActiveRecord (Still UTC in database)
ENV['TZ'] = 'Asia/Taipei' # For ruby
@ascendbruce
ascendbruce / gist:7071046
Created October 20, 2013 15:24
ruby regexp string strip HTML
str.gsub(/<\/?[^>]*>/, "")
@ascendbruce
ascendbruce / gist:7071054
Last active December 26, 2015 01:28
Octopress commands cheatsheet

Create an new post draft

rake new_post["Zombie Ninjas Attack: A survivor's retrospective"]

Multiple categories example

categories: [CSS3, Sass, Media Queries]

rake tasks