Skip to content

Instantly share code, notes, and snippets.

@brianmcallister
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianmcallister/9009230 to your computer and use it in GitHub Desktop.
Save brianmcallister/9009230 to your computer and use it in GitHub Desktop.
Read a JSON file containing breakpoints, and return a Sass list.
{
"desktop": {
"min": 801
},
"tablet": {
"min": 481,
"max": 800
},
"phone": {
"max": 480
}
}
module Sass::Script::Functions
# Public: Get breakpoints from a json file, converted into a Sass list.
# https://gist.github.com/brianmcallister/9009230
#
# filename - Name of the file to read.
#
# Examples
#
# If 'breakpoints.json' looks like this:
# {'desktop': {'min': 801}, 'tablet': {'max': 800, 'min': 481},
# 'phone': {'max': 480}}
#
# You'll get the following:
#
# $breakpoints: get_breakpoints();
# #=> desktop 801, tablet 800, 481, phone 480
#
# Returns a Sass list of breakpoints.
def get_breakpoints(filename = Sass::Script::String.new('breakpoints.json'))
assert_type filename, :String
# Get the file contents.
path = "#{@options[:custom][:javascripts_dir]}/libs/#{filename}"
file = IO.read(path)
# Convert the JSON into a Sass list.
breakpoints = ::JSON.parse(file)
list = []
breakpoints.each do |b|
name = Sass::Script::String.new(b[0])
values = []
values << if b[1]['min'].nil?
Sass::Script::Null.new()
else
Sass::Script::Number.new(b[1]['min'], ['px'])
end
values << if b[1]['max'].nil?
Sass::Script::Null.new()
else
Sass::Script::Number.new(b[1]['max'], ['px'])
end
values = Sass::Script::List.new(values, :comma)
list << Sass::Script::List.new([name, values], :space)
end
return Sass::Script::List.new(list, :comma)
end
declare :get_breakpoints, %w(:filename)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment