Skip to content

Instantly share code, notes, and snippets.

@chsh
Last active April 30, 2021 13:30
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 chsh/670e64d89356a7fd43db3284ee80e10e to your computer and use it in GitHub Desktop.
Save chsh/670e64d89356a7fd43db3284ee80e10e to your computer and use it in GitHub Desktop.
Idea: Writing Tailwind CSS with ruby's method chain.
body(class=tw.text.px_4.py_2.hover__text_gray_200)
button(class=tw.btn.btn_primary) CLICK!
class TailwindStyles
def text
'dark:text-white text-black'
end
def btn
'p-4 rounded-full inline'
end
def btn_primary
'text-white dark:bg-blue-800'
end
end
module TailwindcssHelper
class TailwindStylesChainable
def initialize
@classes = []
@tailwind_styles = TailwindStyles.new
end
attr_reader :classes
def to_s
classes.join(' ')
end
def method_missing(symbol, *args)
if @tailwind_styles.respond_to?(symbol)
self.class.class_eval do
define_method symbol do |*args|
@classes << @tailwind_styles.send(symbol, *args)
self
end
end
__send__(symbol, *args)
elsif symbol.to_s =~ /^[a-z][a-z\d_]+$/
self.class.class_eval do
k = symbol.to_s.gsub('__', ':').gsub('_', '-')
define_method symbol do
@classes << k
self
end
end
__send__(symbol, *args)
else
super
end
end
end
def tw
TailwindStylesChainable.new
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment