Last active
August 29, 2015 14:06
-
-
Save whizark/b42f5d52c3caa2ad5f43 to your computer and use it in GitHub Desktop.
Sass: Typed value factory & validator using Map #sass
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ---- | |
// Sass (v3.4.1) | |
// Compass (v1.0.1) | |
// ---- | |
// Sass: Typed value factory & validator using Map | |
// Direction type that accepts only top, right, left, bottom | |
// Direction type factory | |
@function dir-new($dir) { | |
$is-valid: -dir-validate($dir); | |
// do something | |
// e.g. transform the arguments into proper form. | |
$value: ( | |
-type : 'dir', | |
-value: $dir | |
); | |
@return $value; | |
} | |
// Direction type validator | |
@function -dir-is-valid($dir) { | |
$valid-values: ('top', 'right', 'bottom', 'left'); | |
@return index($valid-values, $dir) != null; | |
} | |
// Validate a value as Direction type | |
@function -dir-validate($dir) { | |
@if -dir-is-valid($dir) { | |
@return true; | |
} | |
@error 'Cannot convert the value `#{inspect($dir)}` into Direction.'; | |
} | |
// Typed Map factory (API) | |
@function new($type, $values...) { | |
$factory : $type + '-new'; | |
@if not function-exists($factory) { | |
@error 'The type `#{$type}` doesn\'t exist.'; | |
} | |
$value: call($factory, $values...); | |
@return $value; | |
} | |
// Check the type of a value (API) | |
@function is-type($type, $value) { | |
@if map-get($value, '-type') == $type { | |
@return true; | |
} | |
@return false; | |
} | |
// Validate a value as a type (API) | |
@function validate($type, $value) { | |
@if is-type($type, $value) { | |
@return true; | |
} | |
@error 'The value `#{inspect($value)}` isn\'t a #{$type}.'; | |
} | |
// Typed Map Getter (API) | |
@function get($map) { | |
@return map-get($map, '-value'); | |
} | |
// Use case | |
@mixin border($dir) { | |
$is-valid : validate('dir', $dir); | |
$dir-value: get($dir); | |
border-#{$dir-value} : 1px solid #000; | |
padding-#{$dir-value}: 1em; | |
} | |
$dir: new('dir', top); | |
.test { | |
dir : inspect($dir); | |
@include border($dir); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.test { | |
dir: (-type: "dir", -value: top); | |
border-top: 1px solid #000; | |
padding-top: 1em; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment