5 ms·
Gem adds support for creating state machines for attributes on any Ruby class
- 38 3y agoI think Ruby is OK enough, but what is this? state_machine :state, initial: :parked do I think in their zeal to "golf" the language, they forgot to actually keep it readable
- aaronbrethorst 3y agoI've been writing Ruby for about 16 years, and I find that eminently readable. You're apply state_machine to the attribute state, and giving it an initial value of :parked. Then there's a block that ostensibly encapsulates state transitions following (hence the do). Ruby can be written extremely tersely, and that can be difficult for non-Rubyists to read. This might help: state_machine(:state, {:initial => :parked}) do # transitions here end What I don't understand is why I'd want use this over aasm (https://github.com/aasm/aasm https://github.com/aasm/aasm)
- filoeleven 3y agoPositionally-significant colons is more nightmarish than significant whitespace. Speaking as a critic of significant whitespace. Put them at the front and make them mean something, or put them at the back and make them mean something, Making both places mean something entirely different, or even allowing both as an allowable syntax, is horrible for readability.
- softjobs 3y agoThe colon sigil denotes a Symbol class literal, and a trailing colon here denotes a Symbol used as a Hash object key.
- rco8786 3y agoRuby uses symbols (strings prefixed with a semicolon) very liberally. It’s just a value literal. Ive never met anyone who writes Ruby that has an issue with the readability of it.
- leetrout 3y agoSelection bias
- fnordpiglet 3y agoI’m a Perl guy, and I find Ruby bizarrely verbose. I don’t understand how people can enjoy their symbols with all those word things.
- donw 3y agoRight? If it doesn't use the shift key and the entire numeric row of the keyboard, count me out.
- rco8786 3y agoWould disagree. I write in other languages and I find things tough to read. There are things about ruby I find tough to read (like `unless`) and know many other people who agree. Symbols work just fine in practice.
- 38 3y agohttps://wikipedia.org/wiki/Stockholm_syndrome https://wikipedia.org/wiki/Stockholm_syndrome
- rco8786 3y agoIs it stockholm syndrome if I leave ruby and years later still wish I had symbols in other languages?
- vidarh 3y agoThey mean "symbol" either way, except when trailing ":" also means they're a key. I'd be inclined to agree it's a wart, but not that it affects readability to any noticeable amount. In this case, though, the DSL looks just awful to me.
- lloeki 3y agoTo expand on this: Contrary to constants which are fixed+ references to values, symbols are pure values: they're like integers but with a textual name. Explicitly they are not strings. They used to be very useful because a symbol takes little memory and comparing two symbols means comparing two integers; it's a bit like `#define FOO 42` in C, except `42` is automatically picked up and you don't care what the value actually is. They are less useful today because there have been a lot of improvements e.g with frozen string literals (which are now stored only once and thus can be compared much more efficiently). Still that has a lot to do as to why they're used for kwargs and hash keys and method names and a ton of other stuff, where without symbols you'd have a ton of the same strings showing up over and over, so instantiated and compared. The hash syntax used to be only arrow but it was so common to do `:foo => "bar"` that at some point Ruby (1.9) introduced `foo: "bar"`, which makes writing hashes look like JSON/YAML and kwargs more like other languages like Python. This does make it a bit surprising because suddenly there's a symbol that is not prefixed with `:` but it also makes things a ton more readable in many cases. I do use the "new hash syntax" liberally, but also still use arrow hashes a lot because it all depends on the way things are written around and sometimes one is more readable than the other. For example in general I don't like writing rake task target dependencies or Rails routes with the new syntax, the arrow one makes more sense to me. Or when one can have mixed keys that can be symbols or some other types, I find it more readable to have a consistent hash syntax, so I go to the old arrow one. + well, although frowned upon, constants can be reassigned, they're essentially just some variables albeit with a different scope and resolution system.
- pdntspa 3y agoIt seems like you have the concept down pat. I don't see what's wrong with it? Like lots of languages use positionally-dependent symbols. In both Perl and VB various characters in the variable name implied things about its type. With C/C++ the position of * tells you lots of important things. How is this anything less than yet another random language quirk?
- nerdponx 3y agoWait, is :state a keyword or an instance attribute? Using the same syntax for both seems really confusing.
- deschutes 3y agoIt's a symbol. Basically a glorified string literal.
- lloeki 3y agoIt's more like an integer with a textual name.
- vidarh 3y agoRuby doesn't have "instance attributes". Instance variables are prefixed with "@". Anything prefixed by ":" is a symbol. In some contexts we use symbols to refer to methods by name. Anything you might thing is an "attribute" is likely a method. E.g. on some_object.name, name is always a method. You might be confused because e.g. "attr_reader" takes symbol arguments, because it's just another method. E.g. "attr_reader :foo" defines a method named "foo" to return "@foo". ":foo" there is a Symbol representing the name "foo".
- nerdponx 3y agoSo it's just a symbol, but in this context it will be used to look up the "state" method? Not unlike how symbols are sometimes used as "designators" of various things in Lisp?
- qudat 3y agoI find it way easier to read this modified version — and I use ruby at work. It’s not even close.
- saghm 3y agoI think the choice to "name" all arguments (`from:`, `to:`, which if I recall from my bygone Ruby days is implicitly parsed as a single hash argument) goes a long way to make things more consistent compared to having the first argument passed separately, making the colons a lot harder to parse visually due to the inconsistency.
- cryo28 3y agoFirst of all these are not new gems. In the past I used both and I strongly prefer this one to aasm. I like the DSL of it. It seems more convenient to me.
- deleted 3y ago[deleted]
- deleted 3y ago[deleted]
- vidarh 3y agoBoth of these gems just feel unreasonable verbose to me. E.g. why "transitions from: :somestate, to: :otherstate" vs just "transition :somestate => : otherstate"? A lot of the syntax of these feels over-engineered, or like someone has just read a Smalltalk introduction and is overdoing keyword arguments to emulate it. If I'm going to use a DSL to define a state machine, it better be a lot terser and/or clearer than a method with a case block. E.g. det state = @state || :initial_statr def state=(event) case [state, event] in [:somestate, :someevent] someaction @state = :newstate in ... ... end end or case event ..., or case state ..., depending on the "shape" of your state machine. ("in" vs "when" here largely depends on whether you want to use any of the newer, fancier pattern matching allowed with "in"; I'm not sure it matters here) I could see wrapping up those two methods in a single small helper, and maybe a little bit extra sugar to make it easier to decompose large state machines, but it better be a complex set if transitions before I'd not throw a fit over the use of these gems in a code review. (Yes, I can see they offer a lot more information about the states and transitions, but I'd argue they offer far too broad APIs for it by default, and you'll end up going hunting for method definitions that don't exist all over the place because of all the methods it injects) In particular the whole before/around/after transition screams at me to apply caution to prevent people having to hunt around to figure out the total set of possible effects of a transition.
- mp1mp2mp3 3y agoOn why not to use "transition :somestate => :otherstate", it would be because then other optional arguments might conflict with the state names. For example, if the `transition` method takes an optional argument of `given:` then a state machine could not have state called `given`. In fact, no optional arguments could be added in a backwards compatible way. The states could be passed positionally but, imo, the increased verbosity helps readability rather than hinders it. Your example code seems not really thought through. If I were to implement that, then I would write code that looked like this: `my_thing.state = :some_action; assert my_thing.state == :some_new_state`. Now we're spending company money discussing whether the state machine code you decided to write by yourself has a reasonable interface. I've used aasm for years and it's just fine. If someone suggested we just implement a non-trivial state machine with our own homegrown solution, I would push back. Trust the community's experience and just pull in the well-established library. There seems to me a certain hubris in deciding that the rest of the world has settled on an overly complex solution when, if they had just thought for a moment, it should just be a 'switch` statement.
- __s 3y agoIt can come as "golf" language, but those features are used to achieve DSL capabilities See how much mileage Lua gets by `f "a"` be `f("a")` or `f{a = 3}` be `f({a = 3})`. Haskell achieves the same
- dymk 3y agoThis is idiomatic Ruby syntax, and anyone familiar with the language knows what that code does
- heleninboodler 3y agoThis is kind of an absurd statement, given how prevalent custom DSLs are in Ruby (and in this example). No amount of familiarity with the Ruby language can tell me what this means: event :ignite do transition stalled: same, parked: :idling end You have to be familiar with the DSL, not Ruby.
- dymk 3y agoIt's generally good practice to read a library's documentation to understand how to use it - there's not really a short cut to that, regardless of the language. As for the syntax, you know that `event` is a method, passed the param `:ignite` and a block, and in that block, you call the method `transition` with kwargs `{stalled: same, parked: :idling}`, and `same` is another method call.
- heleninboodler 3y agoIndeed I know all of this. But in terms of "what this code does," the information that a method is passed a block that calls another method is not particularly interesting. The major problem I have with this sort of DSL is it encourages people to infer what it does based on what the ad hoc method names make it sound like this is intended to do. So many of these custom DSLs are documented by example rather than by any decent specification. The attitude that these clever little grammars make it so you can "just read it and it's obvious" is, in my opinion, sloppiness in code comprehension taken to an extreme.
- bradly 3y agoI don't think this is bad, but my preference would be to change `initial` to `initially`. I'd probably also make :state the default name as well, but that may be too magical for some, especially those not used to Rail's omakase philosophy.
- jrvarela56 3y agoReadability is one of Ruby's strengths. Most custom DSLs I've encountered are easy to understand. Arguably meta programing makes it harder but the language allows you to strike the balance that suits you.
- 38 3y agogood joke
- rco8786 3y agoThis is pretty standard Ruby stuff. It’s different for sure. But works really nicely in practice.
- akerl_ 3y agoIt’s a function call, with a positional arg and a keyword arg?
- deleted 3y ago[deleted]
- kshahkshah 3y agoeveryone in this chain is forgetting to mention a core design principal of Ruby. Matz wants a principal of least surprise. That doesn't mean _your_ least surprise as a non-Ruby programmer, or someone with passing familiarity with the language. It means the least surprise of someone who has worked with the language for years. What Matz has said is that C++ continues to surprise him years and years in, and he _didn't_ want that to be the case for Ruby.
- carlwiedemann 3y agoI've worked extensively on a project that has used this gem. Its reliance on metaprogramming can be cumbersome and difficult to debug. It's kind of funny to me that this is somehow making the front page of HN given that it is a pretty old gem and has many shortcomings, e.g. only getting Ruby 3.x support in the last year.
- deleted 3y ago[deleted]
- ccyphers 3y ago[dead]
- vidarh 3y agoI'm not sure why this is interesting enough to post. It's an old gem, and the DSL seems awfully verbose to me for how little it does. I love Ruby, but I wouldn't want to write Ruby like this...
- deleted 3y ago[deleted]
- vidarh 3y agoToo late to edit this, but here's a toy example of what I'd be more inclined to like for cases complex enough that a purely case-based state machine feels too cumbersome: https://gist.github.com/vidarh/04b7d54c94f1f03b4cf084081166d812 https://gist.github.com/vidarh/04b7d54c94f1f03b4cf084081166d... It's very limited compared to this gem, some on purpose, some because it's a toy. On purpose: Only a single state machine per class; I might be inclined to offer a tiny helper to let you delegate to a (sub-)state machine, but there's little to be gained by not using extra classes as extra namespaces to contain this. The biggest gap is the lack of a lot of little helpers that'd be easy to add if you want (e.g. "state_name?") but that I feel creates little benefit over "state == :state_name", though trivially added if you eg. define an "event(state, &block)" class method that does "define_method(state, block)" and then add whatever extra "define_method"'s you want for introspection. The other big gap is introspection. I think if you need to be able to introspect the state machine, then chances are it's too big to start with and you might want to decompose it. But if you absolutely need that, you can still maintain most of the simplicity of the example I gave. E.g. you can either define a helper to define events (so you'd do e.g. event(:event_name) do ... end instead of def event_name = ...), but you can also use "method_added" and a flag to e.g. wrape the event methods in an "events" block so you can do "events do ... def some_event" and still obtain a list of events. If you do the former, you can return or instance_eval a builder object (personally, and I've done this myself, I think Ruby devs are way too quick to resort to builder/instance_eval DSLs in cases where regular methods work just fine; builders/instance_eval risks creating all kinds of unintended issues). If you do the latter, you can have the helpers honor a "dry run" flag that records the transitions instead. The caveat in both cases is that unlike the example in the gist you can't use the regular Ruby flow control or some transitions and conditions might be "invisible", so you might end up with something like this: events do def repair = if_state(:stalled) do unless_action(:auto_shop_busy) { transition_to(:parked) } end # other events end The change to the helpers to support building a state graph from this is trivial, or if you want you can even conditionally include the "dryrun" version of the helpers as needed.